2012-04-06 56 views
0

所以我在这里发布了这个问题。列表python的排列

permutations of lists python

和解决方案的工作..但我应该更加小心。 请看看上面的链接。

,如果我没有什么有一个明确的列表为A,B,C,d 但我有一个列表的列表..像

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

等。 而在最后,我只有“名单”

在这种情况下,这

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

不工作?

回答

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

+0

嗨。不,基本上我想要列表中的元素的所有排列(如链接中发布).. btw这种方法和类似a + b之间的区别是什么?只是好奇 – Fraz 2012-04-06 06:44:37

+0

并不多,但它接受iterables并返回一个迭代器。 – jamylak 2012-04-06 06:45:46

+0

嗨..太棒了..它的作品..但是什么“*”呢?我想我只是在Python中学到了一些新的东西:) – Fraz 2012-04-06 06:51:00