我有一个列表,列表中有字典,我想按字典值对列表进行排序。
这是如何运作的?
[{'id': 0, 'thread': 'First',
'post': [
{'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:08.939687'}]
},
{'id': 1, 'thread': 'Second',
'post': [
{'id': 0, 'title': 'MyPost', 'time': '2015-11-07 01:06:42.933263'}]},
{'id': 2, 'name': 'NoPosts', 'post': []}]
我想按第一篇文章的时间对我的主题列表进行排序,这可能吗?
您可以传递排序或排序键功能:
In [11]: def key(x):
try:
return x["post"][0]["time"] # return ISO date string
except IndexError:
return "Not a date string" # any letter > all date strings
In [12]: sorted(d, key=key)
Out[12]:
[{'id': 0,
'post': [{'id': 0, 'time': '2015-11-07 01:06:08.939687', 'title': 'MyPost'}],
'thread': 'First'},
{'id': 1,
'post': [{'id': 0, 'time': '2015-11-07 01:06:42.933263', 'title': 'MyPost'}],
'thread': 'Second'},
{'id': 2, 'name': 'NoPosts', 'post': []}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句