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

标签 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) 

最佳答案

相当于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)

关于python - 迭代列表以生成列表中元素的所有可能组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930978/

相关文章:

javascript - JS 数组循环次数为 1 Off

python - 使用 PIL 在 Python 中围绕文本创建光环?

python - 在相同的上下文管理器中执行多个测试

python - 为什么 python getopt 不解析我的选项,而是认为它们是参数?

python - Python中整数平方根的准确性

python - 将 python 中的两个单词列表相交

python - 如何合并列表中的相似项目

python - 即使没有在 for 循环中触及它,列表也会发生变化

php - 从 mysql 行执行 php 脚本

loops - WSO2 ESB 调用参数化端点 Looping on Parameters