【发布时间】:2017-08-13 08:19:56
【问题描述】:
我正在尝试打印出列表中所有可能的元素组合。
import random
def fun(lst, run):
i = 0
while i < run:
newList = lst
NewNumbers = newList[-1:] + newList[:-1] #shifts each element in the to the right
lst = NewNumbers
print(lst)
i += 1
fun([1, 2, 0], 3)
作为初始列表 [1, 2, 0]。这个程序产生输出
>>>>>>>>
[0, 1, 2]
[2, 0, 1]
[1, 2, 0]
>>>>>>>>
我不得不将列表从 [1, 2, 0] 实际更改为 [1, 1, 0] 之类的其他内容,以获得其他可能的组合
>>>>>>>>
[0, 1, 1]
[1, 0, 1]
[1, 1, 0]
>>>>>>>>
然后继续将列表更改为[2, 2, 0], [0, 0, 2] 等以获得其他组合,一旦我将列表增加到 4 个元素,例如[1, 2, 0, 1],这非常耗时且不容易做到
我已经能够找到一种方法来使用 python 的 intertools 来做到这一点
import itertools
def fun(lst):
all_possible_combinations = set(itertools.product(lst, repeat=3)) #repeat = number of elements
return all_possible_combinations
print(fun([0, 1, 2]))
这正是我所寻找的,它生成元素 0、1、2 的所有可能组合类型
{(0, 1, 1), (0, 1, 2), (1, 0, 0), (1, 0, 1), (0, 2, 1), (1, 0, 2), (0, 2, 0), (0, 2, 2), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (1, 1, 0), (2, 2, 2), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (2, 2, 0), (0, 1, 0)}
我正在尝试通过一个循环来生成所有这些组合,该循环通过迭代,例如第一次迭代 (0, 1, 1) 然后第二次迭代 (0, 1, 2) 如下所示:
(0, 1, 1)
(0, 1, 2)
(1, 0, 0)
(1, 0, 1)
【问题讨论】:
标签: python list loops while-loop