Я пытаюсь создать список перестановок в al oop и распечатать для каждой итерации с выводом более двух (или записать в строки файла).
Пример списка ввода:
['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? Я должен использовать комбинации или что-то еще?
Я серьезно застрял, поэтому любая помощь очень ценится!
Спасибо!