本文介绍了Python中一组列表的所有可能排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我有一个n个列表的列表,每个列表具有可变数量的元素.如何创建包含所有可能排列的单个列表:
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
例如
[ [ 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是正确的方法,但它要求我提前知道参数的数量
Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance
推荐答案
使用itertools.product
>>> 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中一组列表的所有可能排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!