[英]All possible permutations of multiple lists and sizes
It's easy in python to calculate simple permutations using itertools.permutations() . 在python中,使用itertools.permutations()计算简单的排列很容易。
You can even find some possible permutations of multiple lists . 您甚至可以找到多个列表的一些可能排列 。
import itertools
s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
for l in list(itertools.product(*s)):
print(l)
('a', 'd', 'e')
('a', 'd', 'f')
('b', 'd', 'e')
('b', 'd', 'f')
('c', 'd', 'e')
('c', 'd', 'f')
It's also possible to find permutations of different lengths . 也可以找到不同长度的排列 。
import itertools
s = [1, 2, 3]
for L in range(0, len(s)+1):
for subset in itertools.combinations(s, L):
print(subset)
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
How would you find permutations of all possible 1) lengths , 2) orders , and 3) from multiple lists ? 您如何从多个列表中找到所有可能的1) 长度 ,2) 阶数和3)的排列?
I would assume the first step would be to combine the lists into one. 我假设第一步是将列表合并为一个。 A list will not de-dup items like a set would. 列表不会像集合那样去重复项目。
s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
('a', 'b')
('a', 'c')
('a', 'd')
('a', 'e')
('a', 'f')
...
('b', 'a')
('c', 'a')
...
('a', 'b', 'c', 'd', 'e')
...
('a', 'b', 'c', 'd', 'e', 'f')
...
('f', 'a', 'b', 'c', 'd', 'e')
Like you suggested, do: 像您建议的那样,执行以下操作:
s = [x for y in s for x in y]
and then use your solution for finding permutations of different lengths: 然后使用您的解决方案查找不同长度的排列:
for L in range(0, len(s)+1):
for subset in itertools.combinations(s, L):
print(subset)
would find: 会发现:
()
('a',)
('b',)
('c',)
('d',)
('e',)
('f',)
('a', 'b')
('a', 'c')
('a', 'd')
('a', 'e')
('a', 'f')
('b', 'c')
('b', 'd')
('b', 'e')
('b', 'f')
('c', 'd')
('c', 'e')
('c', 'f')
('d', 'e')
('d', 'f')
('e', 'f')
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'b', 'e')
('a', 'b', 'f')
('a', 'c', 'd')
('a', 'c', 'e')
('a', 'c', 'f')
('a', 'd', 'e')
('a', 'd', 'f')
('a', 'e', 'f')
('b', 'c', 'd')
('b', 'c', 'e')
('b', 'c', 'f')
('b', 'd', 'e')
('b', 'd', 'f')
('b', 'e', 'f')
('c', 'd', 'e')
('c', 'd', 'f')
('c', 'e', 'f')
('d', 'e', 'f')
('a', 'b', 'c', 'd')
('a', 'b', 'c', 'e')
('a', 'b', 'c', 'f')
('a', 'b', 'd', 'e')
('a', 'b', 'd', 'f')
('a', 'b', 'e', 'f')
('a', 'c', 'd', 'e')
('a', 'c', 'd', 'f')
('a', 'c', 'e', 'f')
('a', 'd', 'e', 'f')
('b', 'c', 'd', 'e')
('b', 'c', 'd', 'f')
('b', 'c', 'e', 'f')
('b', 'd', 'e', 'f')
('c', 'd', 'e', 'f')
('a', 'b', 'c', 'd', 'e')
('a', 'b', 'c', 'd', 'f')
('a', 'b', 'c', 'e', 'f')
('a', 'b', 'd', 'e', 'f')
('a', 'c', 'd', 'e', 'f')
('b', 'c', 'd', 'e', 'f')
('a', 'b', 'c', 'd', 'e', 'f')
If you want to distinguish eg ('d', 'e', 'f')
from ('f', 'e', 'd')
(thanks @Kefeng91 for pointing this out) and others, replace itertools.combinations
with itertools.permutations
, like @YakymPirozhenko suggests. 如果您想区分('d', 'e', 'f')
与('f', 'e', 'd')
(感谢@ Kefeng91指出这一点)和其他,请将itertools.combinations
替换为itertools.permutations
,例如@YakymPirozhenko所建议的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.