Home > Software design >  every combination of numbers in array access list, python
every combination of numbers in array access list, python

Time:03-04

I have a list in python: [5,5,5]. I want to use these number to iterate over every combination of another list like this:

list2[0][0][0], list2[0][0][1], list2[0][0][2] ... up to list2[5][5][5]

if the input list would be [6,7,8,3], then I need to iterate over it like this:

list2[0][0][0][0], list2[0][0][0][1], list2[0][0][0][2] ... up to list2[6][7][8][3]

I have been trying to solve this for 2 days now but cannot wrap my head around how to solve this kind of problem. Thank you for your help!

CodePudding user response:

You can just create a recursive function for that:

def iterate(a: list, loops: list):
    if len(loops) == 0:
        ...  # here you do what you want
        return
    for i in range(loops[0]):
        iterate(a[i], loops[1:])


ar = [
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    [[10, 11, 12], [13, 14, 15], [16, 17, 18]]
]

iterate(ar, [2, 3, 3])

CodePudding user response:

from itertools import product

list1 = [4, 2, 3]
list2 = [
    [[1, 2, 3], [4, 5, 6]],
    [[7, 8, 9], [10, 11, 12]],
    [[13, 14, 15], [16, 17, 18]],
    [[19, 20, 21], [22, 23, 24]],
]

# create iterator of all possible index combinations
indices = product(*(range(i) for i in list1))

for index in indices:

    # start with whole list and consecutively walk over the sublists
    element = list2
    for i in index:
        element = element[i]

    print(element)

# prints the numbers 1 - 24
  • Related