【发布时间】:2015-10-22 10:09:37
【问题描述】:
我正在寻找一种方法来对字典列表进行排序以获得“自然排序顺序”。我找到了模块natsort,但显然我没有正确使用它来正确排序字典列表。谁能帮忙找出我的错误?
这是我的代码:
from operator import itemgetter
import natsort
# Example list an dict
list = ['13h', '1h', '3h']
dict = [{'a': '13h', 'b': 3}, {'a': '1h', 'b': 1}, {'a': '3h', 'b': 0}]
# Sort the list
natsort.natsorted(list, key=lambda y: y.lower())
# Sort the dict
# Later I also want to sort on several keys, therefore the itemgetter
sorted(dic, key=itemgetter(*['a']))
【问题讨论】:
-
你试过了吗 -
natsort.natsorted(dic, key=itemgetter(*['a']))? -
没有。大声笑,它有效。这意味着我已经有了答案:/
-
第一次使用
key=lambda y: y.lower()有什么原因吗?您的数据似乎已经是小写了。
标签: python sorting dictionary natsort