繁体   English   中英

如何使用日期对Python列表进行排序

[英]How to sort Python list with date

我有这样的Python列表

myList = ['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']

我想按日期排序这个列表

使用key lambda sorted

例如:

myList = ['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']

print( sorted(myList, key= lambda x: x.split()[-1], reverse=True) )
print( sorted(myList, key= lambda x: x.split()[-1]) )

输出:

['http://microsoft.com Microsoft 2018-07-12', 'http://apple.com Apple Inc 2018-07-11', 'http://google.com Google 2018-07-10']
['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']

您可以拆分每个字符串,取最后一部分,然后按此部分排序:

myList = [
    'http://apple.com Apple Inc 2018-07-11', 
    'http://google.com Google 2018-07-10',     
    'http://microsoft.com Microsoft 2018-07-12'
]

sorted(myList, key=lambda s: s.split()[-1])

输出:

['http://google.com Google 2018-07-10',
 'http://apple.com Apple Inc 2018-07-11',
 'http://microsoft.com Microsoft 2018-07-12']

您还可以通过将datetime.strptime()应用于key来对列表进行排序:

>>> from datetime import datetime
>>> myList = ['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']
>>> sorted(myList, key=lambda x: datetime.strptime(x.split()[-1], '%Y-%m-%d'))
['http://google.com Google 2018-07-10', 'http://apple.com Apple Inc 2018-07-11', 'http://microsoft.com Microsoft 2018-07-12']

注意:这可能会使其稍微复杂化,因为ISO格式化日期,并且对字符串日期进行完全排序,如其他答案中所示。 使用strptime()只是确保日期按正确的日期格式排序。

这是一个应该在更一般情况下工作的方法:

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM