迭代列表以生成列表中所有可能的元素组合?

时间:2017-03-21 15:10:25

标签: python list loops while-loop

我正在尝试打印列表中所有可能的元素组合。

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) 

3 个答案:

答案 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

答案 1 :(得分:1)

文档中显示了等效于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)

答案 2 :(得分:1)

您可以在此处查看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)]