在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')
答案 0 :(得分:3)
像你建议的那样,做:
s = [x for y in s for x in y]
然后使用您的解决方案来查找不同长度的排列:
for L in range(0, len(s)+1):
for subset in itertools.combinations(s, L):
print(subset)
会找到:
()
('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')
如果你想区分,例如来自('d', 'e', 'f')
的{{1}}(感谢@Kefeng91指出这一点)和其他人('f', 'e', 'd')
将itertools.combinations
替换为itertools.permutations
,如@YakymPirozhenko所示。
答案 1 :(得分:1)
这是一个简单的单行(你可以用 feature_cols
代替 s
)
组合:
[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]
排列:
[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.permutations(feature_cols, i) ]
查看my answer here了解更多详情