dia*_*mym 1 python math automation
我有一组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)
Run Code Online (Sandbox Code Playgroud)
我在这里尝试做的是创建一个随机订单,并将其添加到第二个列表(如果尚不在其中)。但是我觉得必须采取不同的方式,而且我可能做错了。我是python的菜鸟,所以将不胜感激!
您正在permutations()从itertools图书馆中寻找。
from itertools import permutations
# this will create all permutations of length 3 of [0,1,2]
list(permutations(range(3), 3))
# returns:
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
Run Code Online (Sandbox Code Playgroud)