Python中加入元素的所有组合每个列表
问题描述:
我有每个元组的列表中有两个元素:[('1','11'),('2','22'),('3','33'),...n]
Python中加入元素的所有组合每个列表
我怎么会发现,只有一次选择的元组的一个元素每个元组的所有组合?
的示例的结果:
[[1,2,3],[11,2,3],[11,2,3],[11,22,33],[ 11,2,33],[11,22,3],[1,22,3],[1,22,33],[1,2,33]]`
itertools。组合给我所有的组合,但不保留从每个元组中只选择一个元素。
谢谢!
答
In [88]: import itertools as it
In [89]: list(it.product(('1','11'),('2','22'),('3','33')))
Out[89]:
[('1', '2', '3'),
('1', '2', '33'),
('1', '22', '3'),
('1', '22', '33'),
('11', '2', '3'),
('11', '2', '33'),
('11', '22', '3'),
('11', '22', '33')]
答
你看了itertools
documentation?
>>> import itertools
>>> l = [('1','11'),('2','22'),('3','33')]
>>> list(itertools.product(*l))
[('1', '2', '3'), ('1', '2', '33'), ('1', '22', '3'), ('1', '22', '33'), ('11', '2', '3'), ('11', '2', '33'), ('11', '22', '3'), ('11', '22', '33')]
+1:Yay itertools! – jathanism