如果这个问题已经得到解答,我事先表示歉意。我已尽我所能,以有限的术语知识来寻找解决方案。
这是有问题的代码行:
Matrix = list([s0, s1, s2] for s0 in splits[0] for s1 in splits[1] for s2 in splits[2])
基本上,我正在构造一个列表(矩阵),其中包含列表“ Splits”中的所有排列。但是,拆分的大小并不总是相同。例如,有时有4列,并且该行如下所示:
Matrix = list([s0, s1, s2, **s3**] for s0 in splits[0] for s1 in splits[1] for s2 in splits[2] **for s3 in splits[3]**)
如何使这条线适应拆分的长度?即
Matrix = list([s0,s1... , sN] for s0 in splits[0] for s1 in splits[1] ... for sN in splits[N])
谢谢
答案 0 :(得分:1)
将splits
解压缩为itertools.product
的参数:
from itertools import product
splits = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Note: a list of tuples, because product yields tuples
explicit = list((s0, s1, s2) for s0 in splits[0] for s1 in splits[1] for s2 in splits[2])
unpacking = list(product(*splits))
assert explicit == unpacking