【发布时间】:2020-03-08 16:27:31
【问题描述】:
我正在尝试在循环中生成一个排列列表,并为每次迭代打印输出超过两个(或写入文件的行)。
示例输入列表:
['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 的错误部分?我应该使用组合还是其他方式?
我被严重卡住了,所以非常感谢任何帮助!
谢谢!
【问题讨论】:
标签: python loops combinations permutation itertools