Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 不同数量的嵌套for循环_Python_For Loop - Fatal编程技术网

Python 不同数量的嵌套for循环

Python 不同数量的嵌套for循环,python,for-loop,Python,For Loop,目前我有以下问题 一方面,以字符串作为元素的列表数量可变,另一方面,列表中的各个元素需要链接 根据list\u-order的规范,一个列表中的每个元素应与另一个列表中的每个元素组合。您将获得列表\u结果。如果您知道有多少个列表,那么可以使用嵌套for循环进行求解。但是如果列表的数量不同,我该如何完成呢? 我也尝试了递归,但没有成功 list_a = ['A', 'B', 'C'] list_b = ['H', 'I', 'J', 'K', 'L'] list_c = ['1', '2'] li

目前我有以下问题

一方面,以字符串作为元素的列表数量可变,另一方面,列表中的各个元素需要链接

根据
list\u-order
的规范,一个列表中的每个元素应与另一个列表中的每个元素组合。您将获得
列表\u结果
。如果您知道有多少个列表,那么可以使用嵌套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', ...]]

我已经更改了
列表的顺序
,以表示列表中的索引

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

输出

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

为什么要将变量名用作字符串文字?您可能需要一个dict来获取数据。听起来您最终想要访问itertools,然后您可以连接字符串。可能会有帮助。你@user10987432我就是这么想的,它同时起作用,谢谢:)你和@Vicrobot,我也是这么想的,它同时起作用,谢谢:)
[['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']]