英文:
Different number of nested for loops
问题
以下是翻译好的部分:
目前我遇到了以下问题。
一方面,有一系列包含字符串元素的可变数量的列表,另一方面,需要根据list_order
的规范将这些列表的各个元素进行链接。
每个来自一个列表的元素应与来自另一个列表的每个元素根据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', ...]]
英文:
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', ...]]
答案1
得分: 3
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']]
英文:
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']]
答案2
得分: 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))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论