[英]Iterating through a list to produce all possible combinations of elements in a list?
我正在尝试打印出列表中元素的所有可能组合。
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)
此方法使用递归函数生成所有组合的列表,然后可以对其进行迭代。
def product(lst, current, rslt):
if len(current) >= len(lst) - 1:
for item in lst:
rslt += [current + [item]]
else:
for item in lst:
product(lst, current + [item], rslt)
rslt = []
product([0, 1, 2], [], rslt)
for p in rslt:
print p
docs中显示了itertools.product()的纯python等效项:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
您可以在此处查看itertools产品的代码: https ://docs.python.org/3/library/itertools.html#itertools.product
如果您希望函数具有与您的函数相同的变量名,请使用以下产品代码的修改版本来执行所需的操作:
def fun(lst, run):
pools = [lst] * run
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield(tuple(prod))
print(list(fun([1, 2, 0], 3)))
输出:
[(1, 1, 1), (1, 1, 2), (1, 1, 0), (1, 2, 1), (1, 2, 2), (1, 2, 0), (1, 0, 1), (1, 0, 2), (1, 0, 0), (2, 1, 1), (2, 1, 2), (2, 1, 0), (2, 2, 1), (2, 2, 2), (2, 2, 0), (2, 0, 1), (2, 0, 2), (2, 0, 0), (0, 1, 1), (0, 1, 2), (0, 1, 0), (0, 2, 1), (0, 2, 2), (0, 2, 0), (0, 0, 1), (0, 0, 2), (0, 0, 0)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.