列表python的排列

时间:2012-04-06 06:40:43

标签: python list

所以我在这里发布了这个问题。

permutations of lists python

解决方案有效..但我应该更加小心。 请看一下上面的链接。

如果我没有明确列出a,b,c,d怎么办? 但我有一个列表列表..类似

 lists.append(a)
  lists.append(b)

等等。 最后,我所拥有的只是“名单”

for item in itertools.product(lists): 
   print(item)

在这种情况下不起作用??

1 个答案:

答案 0 :(得分:2)

使用*解压缩列表中的所有内容:

>>> import itertools
>>> a = ["1"]
>>> b = ["0"]
>>> c = ["a","b","c"]
>>> d = ["d","e","f"]
>>> lists = [a,b,c,d]
>>> for item in itertools.product(*lists):
        print item


('1', '0', 'a', 'd')
('1', '0', 'a', 'e')
('1', '0', 'a', 'f')
('1', '0', 'b', 'd')
('1', '0', 'b', 'e')
('1', '0', 'b', 'f')
('1', '0', 'c', 'd')
('1', '0', 'c', 'e')
('1', '0', 'c', 'f')

这只是将列表解压缩到其元素中,因此它与调用itertools.product(a,b,c,d)相同。如果您不这样做,itertools.product会将其作为一个项目进行交互,这是一个列表列表[a,b,c,d],当您想要查找列表中四个元素的乘积时。

@sberry发布了这个有用的链接:http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists