简体   繁体   English

不同数量的嵌套 for 循环

[英]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 .根据list_order的规范,一个列表中的每个元素都应该与另一个列表中的每个元素组合。 You get list_result .你得到list_result If you know how many lists there are, then you solve it with nested for loops.如果您知道有多少个列表,那么您可以使用嵌套的 for 循环来解决它。 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 :使用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.我已经更改了list_order来表示列表的 indecies。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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