首页 > 解决方案 > Python中列表从2到N的唯一排列

问题描述

我正在尝试在循环中生成一个排列列表,并为每次迭代打印两个以上的输出(或写入文件的行)。

示例输入列表:

['one', 'two', 'three', 'four']

所需输出:

['one', 'two', 'three', 'four']
['two', 'three', 'four']
['one', 'three', 'four']
['one', 'two', 'four']
['one', 'two']
['one', 'three']
['one', 'four']
['two', 'three']
['two', 'four']
['three', 'four']

这是我迄今为止所管理的(在我的 Python 生命的早期,请原谅):

from itertools import permutations

input = ['one', 'two', 'three', 'four']

def convertTuple(tup): 
    str =  ''.join(tup) 
    return str

while (len(input) > 1):    
    permlist = set(permutations(input))
    for i in permlist:
        print(i)
        i = convertTuple(i)
        outfile = open("out.txt", "w")
        outfile.write(i)
    input = input[:-1]
else:
    print("End of permutation cycle")

哪个输出:

('two', 'three', 'one', 'four')
('two', 'four', 'one', 'three')
('three', 'two', 'one', 'four')
('four', 'two', 'one', 'three')
('two', 'one', 'three', 'four')
('two', 'one', 'four', 'three')
('three', 'one', 'four', 'two')
('four', 'one', 'three', 'two')
('one', 'two', 'three', 'four')
('one', 'two', 'four', 'three')
('three', 'four', 'one', 'two')
('four', 'three', 'one', 'two')
('two', 'three', 'four', 'one')
('two', 'four', 'three', 'one')
('three', 'two', 'four', 'one')
('three', 'four', 'two', 'one')
('four', 'two', 'three', 'one')
('four', 'three', 'two', 'one')
('three', 'one', 'two', 'four')
('four', 'one', 'two', 'three')
('one', 'four', 'two', 'three')
('one', 'three', 'two', 'four')
('one', 'three', 'four', 'two')
('one', 'four', 'three', 'two')
('two', 'three', 'one')
('three', 'two', 'one')
('three', 'one', 'two')
('one', 'two', 'three')
('one', 'three', 'two')
('two', 'one', 'three')
('two', 'one')
('one', 'two')
End of permutation cycle

我明白我错了

input = input[:-1]

因为它只是删除了原始列表中的最后一个值,但我无法弄清楚如何仅获取唯一列表,每个列表中具有不同数量的值...

我是否使用了 itertools 的错误部分?我应该使用组合还是其他东西?

我被严重卡住了,所以非常感谢任何帮助!

谢谢!

标签: pythonloopscombinationspermutationitertools

解决方案


假设 ('one','two','three') 是您想要的列表中的意外遗漏,这应该可以解决问题:

from itertools import combinations

l = ['one', 'two', 'three', 'four']

for size in range(2,len(l)+1):
    for i in combinations(l,size):
        print(i)

推荐阅读