【发布时间】:2018-05-08 20:56:33
【问题描述】:
在 python 中使用itertools.permutations() 计算简单的排列很容易。
你甚至可以找到一些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')
也可以找到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)
您如何从多个列表中找到所有可能的 1) 长度、2) 订单和 3) 的排列?
我假设第一步是将列表合并为一个。列表不会像集合那样删除重复项。
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')
【问题讨论】:
-
如果把列表拉平,不就解决了吗?
-
@BcK 这肯定不是关于扁平化列表的问题的重复。如果有的话,这将是我已经链接到的关于寻找排列的两个问题的重复。但是,我已经解释了问题中的差异。
标签: python list permutation