gpt4 book ai didi

python - 如何按版本键对字典进行排序

转载 作者:行者123 更新时间:2023-12-01 03:39:37 25 4
gpt4 key购买 nike

输入:

foo = {
'testing-1.30.5': ['The', 'quick'],
'testing-1.30.12': ['fox', 'jumped', 'over'],
'testing-1.30.13': ['the'],
'testing-1.30.4': ['lazy', 'dog'],
'testing-1.30.1': ['brown'],
'testing-1.30.3': ['the'],
'testing-1.30.6': ['brown'],
'testing-1.30.2': ['fox', 'jumped', 'over'],
'testing-1.30.14': ['lazy', 'dog'],
'testing-1.30.8': ['the'],
'testing-1.30.0': ['The', 'quick'],
'testing-1.30.10': ['The', 'quick'],
'testing-1.30.11': ['brown'],
'testing-1.30.7': ['fox', 'jumped', 'over'],
'testing-1.30.9': ['lazy', 'dog']
}

进行一些排序

bar = sortfoo(foo)

期望的输出:

for item in bar:
print '{}: {}'.format(item, bar[item])



testing-1.30.0: ['The', 'quick']
testing-1.30.1: ['brown']
testing-1.30.2: ['fox', 'jumped', 'over']
testing-1.30.3: ['the']
testing-1.30.4: ['lazy', 'dog']
testing-1.30.5: ['The', 'quick']
testing-1.30.6: ['brown']
testing-1.30.7: ['fox', 'jumped', 'over']
testing-1.30.8: ['the']
testing-1.30.9: ['lazy', 'dog']
testing-1.30.10: ['The', 'quick']
testing-1.30.11: ['brown']
testing-1.30.12: ['fox', 'jumped', 'over']
testing-1.30.13: ['the']
testing-1.30.14: ['lazy', 'dog']

理想情况下,我希望这是Pythonic的,因为我不会做一些疯狂的事情,比如将 key 拆分成组件并基于此构建一个新字典;

我尝试过的:

from collections import OrderedDict
od = OrderedDict(sorted(foo.items()))
print '{}: {}'.format(item, od[item])

谢谢

最佳答案

明白了!没关系,找到了 LooseVersion/strict 版本

from distutils.version import LooseVersion
from collections import OrderedDict

orderedKeys = sorted(foo, key=LooseVersion)

odict = OrderedDict((key, foo[key]) for key in orderedKeys)

for item in odict:
print '{}: {}'.format(item, odict[item])

关于python - 如何按版本键对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839726/

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