python - 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 的错误部分?我应该使用组合还是其他东西?
我被严重卡住了,所以非常感谢任何帮助!
谢谢!
解决方案
假设 ('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)
推荐阅读
- c# - 如何从从委托集合中调用委托项目的父项运行子任务?
- node.js - 变量作为参数传递给函数和局部变量
- python - 使用python将数据从文件插入到mysql时出错
- python - 如何根据数据框中的值绘制带有颜色的表格?
- arrays - 从文件创建一个数组并根据 bash 中的一行命名
- javascript - 如何检查特定类的所有对象是否也共享另一个类?
- terraform - Azure,terraform 报告 network_interface_id 必须是单个值,而不是创建内部负载均衡器时的列表
- php - 使用 PHP 传递正文标头
- java - Artifactory 无法安装为 Windows 服务
- .htaccess - .htaccess RedirectMatch 排除 index.html