大佬教程收集整理的这篇文章主要介绍了将排列结果从元组更改为列表,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试创建一个列表,其中包含 int 1~6 的所有可能排列。我希望得到的是 [[1,2,3,4,5,6],[1,6,5].....] 但不断得到元组。有没有什么优雅的方式来做下面的代码?
n=6
numberPool = []
for i in range(1,n+1):
numberPool.append(i)
nutPool = List(permutations(numberPool))
# change to List from tuple
temp = []
for i in nutPool:
temp.append(List(i))
nutPool = temp
简单地说,您可以使用推导式将每个元组更改为列表:
nutPool = [list(perm) for perm in permutations(numberPool)]
本质上是将问题中的这五行浓缩为一个表达式:
nutPool = list(permutations(numberPool))
temp = []
for i in nutPool:
temp.append(list(i))
nutPool = temp
,
您可以直接对排列使用列表推导式:
from itertools import permutations
n=6
numberPool = []
for i in range(1,n+1):
numberPool.append(i)
nutPool = [list(perm) for perm in permutations(numberPool)]
print(nutPool)
#[[1,2,3,4,5,6],[1,6,5],4],3],2],[2,1,1],[3,[4,[5,[6,1]]
以上是大佬教程为你收集整理的将排列结果从元组更改为列表全部内容,希望文章能够帮你解决将排列结果从元组更改为列表所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。