python - Python中一组列表的所有可能排列

标签 python list permutation

在 Python 中,我有一个包含 n 个列表的列表,每个列表都有可变数量的元素。如何创建一个包含所有可能排列的列表:

例如

[ [ a, b, c], [d], [e, f] ]

我想要

[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]

请注意,我事先并不知道 n。我认为 itertools.product 是正确的方法,但它需要我提前知道参数的数量

最佳答案

使用itertools.product

不需要提前知道n
>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]

关于python - Python中一组列表的所有可能排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2853212/

相关文章:

python - 如何使用列表中的值格式化字符串?

c# - 创建新元素将删除 C# 列表中的第一个元素

r - 如何计算数据框中值序列的出现次数?

java - 字符串排列Java

c# - 在 C# 中,如何检查列表内的重复元素,然后打印重复元素的名称?

c++ - 来自两个列表的随机对

python - 如何确保用户在discord.py 中输入完整命令?

python - 在 Pandas str.contains() 中使用正则表达式中的变量

python - python中的正则表达式和unicode utf-8?

jquery - 如何在包含DIV点击时将 anchor 文本设置为当前?