Python itertools 获取list列表的排列组合

Python itertools get permutations and combinations of a list of lists

当我试图弄清楚如何获得 Python 中列表列表的所有排列和组合时,我的大脑要爆炸了。问题是编写一个函数,它将针对以下输入列表 [['I1', 'I2', 'I3'], ['I2', 'I3']] return 以下内容:

[['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. 函数应该 return 任何大小列表的输入列表的所有排列和组合,而不仅仅是显示的二元列表以上

作为全功能方法,您可以使用 itertools 模块中的 permutations()product() 以及 chain() 函数和内置函数 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])