我有一个这样的 Python 列表
myList = ['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']
我想按日期对这个列表进行排序
最佳答案
下面是一个适用于更一般情况的方法:
from dateutil.parser import parse
myList = [
'http://google.com Google 2018-07-10',
'http://apple.com Apple Inc 2018-07-11',
'Foo 2017-07-13 http://whatever.com',
'http://microsoft.com Microsoft 2018-07-12',
'2015-07-15 http://whatever.com Whatever'
]
dct = {parse(v, fuzzy=True): v for v in myList}
print([dct[k] for k in sorted(dct, reverse=True)])
print([dct[k] for k in sorted(dct)])
这样你就不会被迫在列表字符串的末尾有日期,输出:
['http://microsoft.com Microsoft 2018-07-12', 'http://apple.com Apple Inc 2018-07-11', 'http://google.com Google 2018-07-10', 'Foo 2017-07-13 http://whatever.com', '2015-07-15 http://whatever.com Whatever']
['2015-07-15 http://whatever.com Whatever', 'Foo 2017-07-13 http://whatever.com', 'http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']
关于python - 如何使用日期对 Python 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652979/