【问题标题】:All possible permutations of multiple lists and sizes多个列表和大小的所有可能排列
【发布时间】: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


【解决方案1】:

按照你的建议,做:

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') 来自('f', 'e', 'd')(感谢@Kefeng91 指出这一点)和其他人,将itertools.combinations 替换为itertools.permutations,就像@YakymPirozhenko 建议的那样。

【讨论】:

  • 目前解决方案不错,但无法处理不同的订单。
  • 你有(反)例子吗?
  • @fferri 我认为如果您将combinations 替换为permutations,这将起作用,这正是OP 想要的。
【解决方案2】:

这是一个简单的单行(你可以替换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

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2020-07-16
    • 2017-11-13
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多