gpt4 book ai didi

python : Sort a dictionary by using keys in ascending order

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:54 24 4
gpt4 key购买 nike

我有以下字典,我想使用键对其进行升序排序。

animMeshes = { "anim 0" : 23, "anim 32": 4, "anim 21" : 5, "anim 2" : 66, "anim 11" : 7 , "anim 1" : 5}

我尝试使用:

for mesh,val in sorted(animMeshes.items(), key=lambda t: t[0]):
print mesh

对/对:

anim 0
anim 1
anim 11
anim 2
anim 21
anim 32

我怎样才能得到:

anim 0
anim 1
anim 2
anim 11
anim 21
anim 32

最佳答案

对于您的具体情况,这可以工作:

for mesh,val in sorted(animMeshes.items(), key=lambda t: int(t[0].split()[1])):
print mesh

为什么?因为你的 key 都是以 'anim' 开头,然后有一个数字......

我使用了到 int() 的转换来实现按数字排序。

关于 python : Sort a dictionary by using keys in ascending order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20125837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com