Skip to main content
 首页 » 编程设计

python之python中一组项目的所有可能顺序的列表

2025年05月04日14leader

我有一组 6 个项目,我们称它们为“1”到“6”。我想要做的是创建另一个列表,其中包含这些项目的所有可能组合(订单?)。意味着在所有可能的组合中,必须包含所有 6 项并且不能重复。它可能是反向组合,因为它是一组不同的数字。

这是我的想法:

import random 
 
items = [1,2,3,4,5,6] 
ListOfCombinations = [] 
while True: 
    random.shuffle(items) 
    print(items) 
    string = " ".join(str(e) for e in items) 
    if string not in ListOfCombinations: 
        ListOfCombinations.append(string) 

我在这里尝试做的是创建一个随机顺序并将其添加到第二个列表中(如果它尚未在其中)。但我觉得必须有一种不同的做事方式,我可能做错了。我是 python 的菜鸟,所以帮助将不胜感激!

请您参考如下方法:

您正在从 itertools 库中寻找 permutations()。

from itertools import permutations 
 
# this will create all permutations of [0,1,2] 
list(permutations(range(3))) 
 
# returns: 
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]