简体   繁体   中英

Different number of nested for loops

Currently I have the following problem.

On the one hand, there is a variable number of lists with strings as elements, on the other hand there are variations in which the individual elements of the lists are need to be linked.

Each element from one list should be combined with each element from another list according to the specification of list_order . You get list_result . If you know how many lists there are, then you solve it with nested for loops. But how do I get it done if the number of lists varies? I also tried recursion, but it did not work.

list_a = ['A', 'B', 'C']
list_b = ['H', 'I', 'J', 'K', 'L']
list_c = ['1', '2']

list_order = [['list_a', 'list_b', 'list_c'], ['list_b', 'list_c']]

list_result = [['AH1', 'AH2', 'AI1', 'AI2', ...], ['H1', 'H2', 'I1', 'I2', ...]]

Use itertools.product :

from itertools import product as pd
list_result = [[''.join(k) for k in pd(*[eval(i) for i in j])] for j in list_order]
print(list_result)

Output

[['AH1', 'AH2', 'AI1', 'AI2', 'AJ1', 'AJ2', 'AK1', 'AK2', 'AL1', 'AL2', 'BH1', 'BH2', 'BI1', 'BI2', 'BJ1', 'BJ2', 'BK1', 'BK2', 'BL1', 'BL2', 'CH1', 'CH2', 'CI1', 'CI2', 'CJ1', 'CJ2', 'CK1', 'CK2', 'CL1', 'CL2'], ['H1', 'H2', 'I1', 'I2', 'J1', 'J2', 'K1', 'K2', 'L1', 'L2']]

I've changed the list_order to represent indecies to the lists.

from itertools import product

list_a = ['A', 'B', 'C']
list_b = ['H', 'I', 'J', 'K', 'L']
list_c = ['1', '2']

lists = [list_a, list_b, list_c]

list_order = [[0, 1, 2], [1, 2]]

for order in list_order:
    current_lists = [lists[index] for index in order]
    for tpl in product(*current_lists):
        print("".join(tpl))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM