繁体   English   中英

从单个列表中获取所有可能的列表排列而不重复

[英]Get all possible permutations of lists from a single list without duplicates

我正在尝试获取列表的所有排列。 所以[2, 2, 1]会输出一个输出为(2, 2, 1), (2, 1, 2), (1, 2, 2)的生成器。 我已经尝试了几种方法来做到这一点,但都没有奏效。 例如, itertools.product不起作用。 例如,当我使用itertools.product时,output 是(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2) 即使我只输入了一个 1, itertools.product也以某种方式在一些列表中获得了三个 1。有没有办法在生成器中完全实现我想要的而不生成重复项

据我所知,您想打印可以用这些数字进行的可能排列。 如果那是你想要的,那么你可以使用排列

这是一个代码来说明它

from itertools import permutations


permutation = permutations([2, 2, 1],3)
output = []
for i in list(permutation):
    if i not in output:
        output.append(i)
        
print(output)





您可以使用numpy.roll在索引之间移动1 在产生结果的 function 中执行此操作以创建生成器 object

import numpy as np

def roll(lst):
    for _ in range(len(lst)):
        lst = np.roll(lst, -1)
        yield tuple(lst)

lst = roll([2, 2, 1])
print(lst) # <generator object roll at 0x000001E1D915AAC0>
print(list(lst)) # [(2, 1, 2), (1, 2, 2), (2, 2, 1)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM