程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了将排列结果从元组更改为列表大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决将排列结果从元组更改为列表?

开发过程中遇到将排列结果从元组更改为列表的问题如何解决?下面主要结合日常开发的经验,给出你关于将排列结果从元组更改为列表的解决方法建议,希望对你解决将排列结果从元组更改为列表有所启发或帮助;

我正在尝试创建一个列表,其中包含 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,请注明来意。
标签: