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

标签 python combinations permutation python-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. 该函数应返回任意大小的列表的输入列表的所有排列和组合,而不仅仅是上面显示的二元素列表

最佳答案

作为一种完整的功能方法,您可以使用 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 函数将排列映射到子列表上,然后product 将创建排列的乘积。

作为另一种方式(稍微快一些),您可以使用列表理解代替 map():

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

关于Python itertools 获取列表列表的排列和组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36080799/

相关文章:

python - 如何设置 igraph 图的大小?

r - 将三份副本拆分为副本

scala - Scala 中的整数分区

algorithm - 生成第 25 个元素集的排列,在计算机上是否可行?

Python 箭头添加小时/分钟/等 vs 替换

python - Django部署: ImportError: Could not import settings 'settings.py' (Is it on sys.路径?): No module named settings. py

c++ - 确定两个字符串是否互为排列的程序的时间复杂度

C++:组合算法

python - 生成位于圆内的网格坐标

C# - 迭代数组内容的所有可能成对组合