不同数量的嵌套for循环

时间:2020-01-06 16:23:06

标签: python for-loop

当前我有以下问题。

一方面,存在数量可变的以字符串为元素的列表,另一方面,存在一些变体,其中需要链接列表的各个元素。

应该根据list_order的说明,将一个列表中的每个元素与另一个列表中的每个元素组合。您得到list_result。如果您知道有多少个列表,则可以使用嵌套的for循环来解决。但是,如果列表数量不同,我该如何完成呢? 我也尝试过递归,但是没有用。

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', ...]]

2 个答案:

答案 0 :(得分:3)

使用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)

输出

[['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']]

答案 1 :(得分:1)

我更改了list_order来表示列表中的索引。

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))