0

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

列表python的排列

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

如果我没有明确的列表作为 a,b,c,d 但我有一个列表列表.. 类似

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

等等。最后我只有“列表”

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

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

4

1 回答 1

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

于 2012-04-06T06:43:01.560 回答