如何排列/组合不同大小的列表?python
我有一个列表,内部列表的编号未知: 我需要按照lol列表的顺序从内部列表中的每个项目中获取组合,我一直在这样做以获得所需的输出:如何排列/组合不同大小的列表?python,python,list,itertools,lambda,Python,List,Itertools,Lambda,我有一个列表,内部列表的编号未知: 我需要按照lol列表的顺序从内部列表中的每个项目中获取组合,我一直在这样做以获得所需的输出: >>> for i in x: ... for j in y: ... for k in z: ... print [i,j,k] ... [1, 4, 8] [1, 5, 8] [1, 6, 8] [1, 7, 8] [2, 4, 8] [2, 5, 8] [2, 6, 8]
>>> for i in x:
... for j in y:
... for k in z:
... print [i,j,k]
...
[1, 4, 8]
[1, 5, 8]
[1, 6, 8]
[1, 7, 8]
[2, 4, 8]
[2, 5, 8]
[2, 6, 8]
[2, 7, 8]
[3, 4, 8]
[3, 5, 8]
[3, 6, 8]
[3, 7, 8]
>>> from itertools import product
>>> for i in product(lol):
... print i
...
([1, 2, 3],)
([4, 5, 6, 7],)
([8],)
什么是蟒蛇的方式做上述?是否有用于此的itertools函数
我尝试了itertools.product,但没有获得所需的输出:
>>> for i in x:
... for j in y:
... for k in z:
... print [i,j,k]
...
[1, 4, 8]
[1, 5, 8]
[1, 6, 8]
[1, 7, 8]
[2, 4, 8]
[2, 5, 8]
[2, 6, 8]
[2, 7, 8]
[3, 4, 8]
[3, 5, 8]
[3, 6, 8]
[3, 7, 8]
>>> from itertools import product
>>> for i in product(lol):
... print i
...
([1, 2, 3],)
([4, 5, 6, 7],)
([8],)
你真的很接近:
>>> for i in product(*lol):
... print i
...
(1, 4, 8)
(1, 5, 8)
(1, 6, 8)
(1, 7, 8)
(2, 4, 8)
(2, 5, 8)
(2, 6, 8)
(2, 7, 8)
(3, 4, 8)
(3, 5, 8)
(3, 6, 8)
(3, 7, 8)
在中,有像productA、B这样的示例。因此,您应该将每个列表作为参数传递。在你的例子中,productx,y,z会起作用。*lol符号表示。itertools.product为每个集合使用单独的参数,而不是包含这些集合的单个iterable
for i in product(*lol):
print i
正如其他答案所建议的,你需要解开lol。 另外,在我看来,列表理解更像是一种恶作剧:
import itertools
x = [1,2,3]
y = [4,5,6,7]
z = [8]
lol = [x,y,z]
print [each for each in itertools.product(*lol)] # or set()
[(1, 4, 8), (1, 5, 8), (1, 6, 8), (1, 7, 8), (2, 4, 8), (2, 5, 8), (2, 6, 8), (2, 7, 8), (3, 4, 8), (3, 5, 8), (3, 6, 8), (3, 7, 8)]
你是说产品,哈哈?