【问题标题】:Python sort a list by value of a dict inside the listPython按列表中dict的值对列表进行排序
【发布时间】:2015-11-07 01:04:30
【问题描述】:

我有一个列表,在列表中我有一个字典,我想按字典的值对列表进行排序。

这是如何工作的?

[{'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': []}]

我想按第一次发帖的时间对我的话题列表进行排序,可以吗?

【问题讨论】:

    标签: python list sorting dictionary


    【解决方案1】:

    您可以通过排序或排序的关键功能:

    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': []}]
    

    【讨论】:

    • 不需要return float('NaN') 才能使# NaN > all date strings 为真吗?然后你失去了对 Python 3 的支持......
    • 未指定没有time 的帖子所需的行为,因此'NaN' 听起来不错。
    • 但是"NaN" 只是一个字符串。它需要是float('NaN'),实际上是数字nan。并且 Python3 会抛出 TypeError: unorderable types: float() < str() 它应该是空格字符或 ASCII 中的波浪号用于字符串比较。
    • 好吧,其他值也是字符串,所以 'NaN' 值将简单地位于这个 asciibetical 排序的末尾。理想情况下,这些日期字符串将存储为 datetime 对象。
    • @dawg 我在 python 3 上执行此操作(现在是 2015 年:p)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    相关资源
    最近更新 更多