Python itertools获得列表列表的排列和组合

时间:2016-03-18 09:34:28

标签: python combinations permutation itertools

当我试图弄清楚如何在Python中获取列表列表的所有排列和组合时,我的大脑将会爆炸。问题是编写一个函数,以便以下输入列表[['I1', 'I2', 'I3'], ['I2', 'I3']]返回以下内容:

[['I1', 'I2', 'I3'], ['I2', 'I3']]
[['I1', 'I3', 'I2'], ['I2', 'I3']]
[['I2', 'I1', 'I3'], ['I2', 'I3']]
[['I2', 'I3', 'I1'], ['I2', 'I3']]
[['I3', 'I1', 'I2'], ['I2', 'I3']]
[['I3', 'I2', 'I1'], ['I2', 'I3']]
[['I1', 'I2', 'I3'], ['I3', 'I2']]
[['I1', 'I3', 'I2'], ['I3', 'I2']]
[['I2', 'I1', 'I3'], ['I3', 'I2']]
[['I2', 'I3', 'I1'], ['I3', 'I2']]
[['I3', 'I1', 'I2'], ['I3', 'I2']]
[['I3', 'I2', 'I1'], ['I3', 'I2']]
[['I2', 'I3'], ['I1', 'I2', 'I3']]
[['I2', 'I3'], ['I1', 'I3', 'I2']]
[['I2', 'I3'], ['I2', 'I1', 'I3']]
[['I2', 'I3'], ['I2', 'I3', 'I1']]
[['I2', 'I3'], ['I3', 'I1', 'I2']]
[['I2', 'I3'], ['I3', 'I2', 'I1']]
[['I3', 'I2'], ['I1', 'I2', 'I3']]
[['I3', 'I2'], ['I1', 'I3', 'I2']]
[['I3', 'I2'], ['I2', 'I1', 'I3']]
[['I3', 'I2'], ['I2', 'I3', 'I1']]
[['I3', 'I2'], ['I3', 'I1', 'I2']]
[['I3', 'I2'], ['I3', 'I2', 'I1']]

如何在Python中高效地创建它?谢谢!

P.S。该函数应返回任何大小的列表输入列表的所有排列和组合,而不仅仅是上面显示的两元素列表

1 个答案:

答案 0 :(得分:1)

作为一种全功能方法,您可以使用permutations()模块中的product()chain()以及itertools函数,并内置函数map()

>>> from itertools import permutations, product, chain
>>> def my_prod(lst):
...     return product(*map(permutations, lst))
... 
>>> 
>>> list(chain(*map(my_prod, permutations(lst))))
[(('I1', 'I2', 'I3'), ('I2', 'I3')), (('I1', 'I2', 'I3'), ('I3', 'I2')), (('I1', 'I3', 'I2'), ('I2', 'I3')), (('I1', 'I3', 'I2'), ('I3', 'I2')), (('I2', 'I1', 'I3'), ('I2', 'I3')), (('I2', 'I1', 'I3'), ('I3', 'I2')), (('I2', 'I3', 'I1'), ('I2', 'I3')), (('I2', 'I3', 'I1'), ('I3', 'I2')), (('I3', 'I1', 'I2'), ('I2', 'I3')), (('I3', 'I1', 'I2'), ('I3', 'I2')), (('I3', 'I2', 'I1'), ('I2', 'I3')), (('I3', 'I2', 'I1'), ('I3', 'I2')), (('I2', 'I3'), ('I1', 'I2', 'I3')), (('I2', 'I3'), ('I1', 'I3', 'I2')), (('I2', 'I3'), ('I2', 'I1', 'I3')), (('I2', 'I3'), ('I2', 'I3', 'I1')), (('I2', 'I3'), ('I3', 'I1', 'I2')), (('I2', 'I3'), ('I3', 'I2', 'I1')), (('I3', 'I2'), ('I1', 'I2', 'I3')), (('I3', 'I2'), ('I1', 'I3', 'I2')), (('I3', 'I2'), ('I2', 'I1', 'I3')), (('I3', 'I2'), ('I2', 'I3', 'I1')), (('I3', 'I2'), ('I3', 'I1', 'I2')), (('I3', 'I2'), ('I3', 'I2', 'I1'))]

此处map功能会映射您的子列表中的permutations,然后product将创建排列产品。

另一种方式(并且速度稍快)你可以使用列表理解而不是map()

>>> def my_prod(lst):
...     return product(*[permutations(sub) for sub in  lst])