python列表排列

时间:2012-05-28 09:28:38

标签: python list

  

可能重复:
  How to generate all permutations of a list in Python

我获得了一个列表[1,2,3],任务是创建此列表的所有可能的排列。

预期产出:

[[1, 2, 3], [1, 3, 2], [2, 3, 1], [2, 1, 3], [3, 1, 2], [3, 2, 1]]

我甚至无法从哪里开始思考。有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:3)

itertools.permutations为你做这件事。

否则,一个简单的方法是递归地查找排列:连续选择输出的第一个元素,然后让你的函数找到剩余元素的所有排列。

https://stackoverflow.com/a/104436/42973可以找到略有不同但相似的解决方案。它找到剩余(非第一个)元素的所有排列,然后在所有可能的位置连续插入第一个元素。

答案 1 :(得分:-1)

这是一个基本的解决方案...... 我们的想法是使用递归来遍历所有排列并拒绝无效的排列。

    def perm(list_to_perm,perm_l,items,out):
        if len(perm_l) == items:
            out +=[perm_l]
        else:
            for i in list_to_perm:
                if i not in perm_l:
                    perm(list_to_perm,perm_l +[i],items,out)


a = [1,2,3]
out = []
perm(a,[],len(a),out)
print out

输出:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]