简体   繁体   English

Python 2.7动态长度列表理解

[英]Python 2.7 Dynamic length list comprehension

I apologize in advance if this question has already been answered. 如果这个问题已经得到解答,我提前致歉。 I have done my best to search for a solution with my limited knowledge of terminology. 我已尽我所能,以我有限的术语知识来寻找解决方案。

This is the line of code in question: 这是有问题的代码行:

Matrix = list([s0, s1, s2] for s0 in splits[0] for s1 in splits[1] for s2 in splits[2])

Basically, I'm constructing a list (Matrix) with all permutations in the list of lists, "Splits". 基本上,我正在使用列表“ Splits”中的所有排列构造一个列表(矩阵)。 However, Splits is not always the same size. 但是,拆分的大小并不总是相同。 For instance, sometimes there are 4 columns and the line would look like this: 例如,有时有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]**)

How can I make this line adaptive to the length of Splits? 如何使这条线适应拆分的长度? Ie

Matrix = list([s0,s1... , sN] for s0 in splits[0] for s1 in splits[1] ... for sN in splits[N])

Thank you 谢谢

Unpack splits into the arguments to itertools.product : 解压splitsitertools.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

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

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