Python two-dimensional list, each sublist (with different number of elements) takes one element to combine, listing all possible situations

for example, the known two-dimensional list [[aformab], [dpene], [f]] requires an element from each sublist to be added and lists all the combinations. The output of this question is adf,aef,bdf,bef,cdf,cef. There are many such lists, and the number of sublists is not necessarily the same. Please tell me how to deal with it with python

Feb.26,2021

>>> import itertools
>>> s = [['a','b','c'],['d','e'],['f']]
>>> [''.join(i) for i in itertools.product(*s)]
['adf', 'aef', 'bdf', 'bef', 'cdf', 'cef']

not much, code

-sharp!/usr/bin/python

arr = [
    [
        'a', 'b', 'c',
    ],
    [
        'd', 'e',
    ],
    [
        'f', 'g', 'h'
    ]
]



result = []
length = 1
for row in arr:
    length *= len(row) 

-sharp 
for i in range(0, length):
    result.append([])

for row in arr:
    i = 0
    while i < len(result):
        for letter in row:
            result[i].append(letter)
            i += 1

for row in result:
    print ",".join(row)

of course uses recursion.
for the example you give, processing the entire list is equivalent to processing the result of [[d, e], [f]] (assuming x) plus traversing the first item [a, b, c], that is, the final result. As for the processing of [[d, e], [f]], you can continue to recurse

.
Menu