【问题标题】:Python all permutations of a list [duplicate]Python列表的所有排列[重复]
【发布时间】:2014-01-13 15:10:21
【问题描述】:

嘿,我有一个列表,我想在其中获取它的所有不同排列,即 [A,B,C]。

我想要它的所有不同组合。像这样 [A,C,B], [B,A,C], [B,A,C], [C,A,B] 和 [C,B,A] 我尝试使用 itertools.combinations 我得到所有组合,但不是所有字母都在使用的组合。

matriks = ["A","B","C"]
    combs=[]
    for i in xrange(1, len(matriks)+1):
    els = [list(x) for x in itertools.combinations(matriks, i)]
    combs.append(els)
print(combs)

这给出了以下输出

[[['A'], ['B'], ['C']], [['A', 'B'], ['A', 'C'], ['B', 'C']], [['A', 'B', 'C']]]

【问题讨论】:

  • “组合”和“排列”是不同的东西。听起来你想要后者。
  • 是的,不认识这个词。排列是我想要的

标签: python list sorting swap itertools


【解决方案1】:

你可以简单地使用itertools.permutations:

>>> from itertools import permutations
>>> 
>>> l = ["A","B","C"]
>>> 
>>> list(permutations(l))
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    相关资源
    最近更新 更多