gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:10 25 4
gpt4 key购买 nike

我有一组 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)]

关于python - python中一组项目的所有可能顺序的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com