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

标签 python python-3.x

我有一个这样的 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/

相关文章:

python - 通过 Python 连接 CISCO Anyconnect VPN

python - 在 Pandas 中结合多种风格

python - pandas:处理具有大量字符串的 DataFrame

python - 有没有办法在 python 脚本中执行 arp -a cmd 命令?

Python:错误处理递归函数错误

python - 如何为我的类(class)构造多项式序列?

python - 任务列表输出

python - Python 3 中的不可变字典 : how to make keys(), items() 和 values() 字典 View 不可变

python - 使用 Matplotlib 绘制网格

Python 3 : Functions dependent on other functions, 缺少参数?