搜索

首页  >  问答  >  正文

python 字典比较

一个列表当中有一个日期的值,我想求这个日期里面当天最大时间的那一条,大神们如何写呢?
原始列表
`

    [{
    "count": 0,
    "create_time": "2017-03-22 22:00:00",
    "level": "1"
  },
  {
    "count": 5,
    "create_time": "2017-03-22 22:00:00",
    "level": "0"
  },
  {
    "count": 5,
    "create_time": "2017-03-22 22:00:00",
    "level": "2"
  },
  {
    "count": 5,
    "create_time": "2017-03-22 23:00:00",
    "level": "0"
  },
  {
    "count": 0,
    "create_time": "2017-03-22 23:00:00",
    "level": "1"
  },
  {
    "count": 5,
    "create_time": "2017-03-22 23:00:00",
    "level": "2"
  }]`
  

想要输出的列表

[{
        "count": 5,
        "create_time": "2017-03-22 23:00:00",
        "level": "0"
      },
      {
        "count": 0,
        "create_time": "2017-03-22 23:00:00",
        "level": "1"
      },
      {
        "count": 5,
        "create_time": "2017-03-22 23:00:00",
        "level": "2"
      }]
大家讲道理大家讲道理2785 天前588

全部回复(3)我来回复

  • PHP中文网

    PHP中文网2017-04-18 10:31:04

    在上次问的问题里改sum成max:

    from collections import defaultdict
    grouped = defaultdict(list)
    
    for d in s:
        grouped[(d['create_time'].split()[0], d['level'])].append((d['create_time'], d['count']))
    summed = {k : max(grouped[k]) for k in grouped}
    s = [{'count': summed[k][1], 'create_time': summed[k][0], 'level': k[1]} for k in summed]

    回复
    0
  • PHPz

    PHPz2017-04-18 10:31:04

    像这类问题都可以用groupby来解决

    # coding: utf-8
    
    from itertools import groupby
    
    data = [...]
    fun_group = lambda x: x['level']
    fun_max = lambda x: x['create_time']
    lst = [max(list(g), key=fun_max) for k, g in groupby(sorted(data, key=fun_group), fun_group)]
    print lst

    回复
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:31:04

    思路就是先排序,再过滤

    ls =  [{
        "count": 0,
        "create_time": "2017-03-22 22:00:00",
        "level": "1"
      },
      {
        "count": 5,
        "create_time": "2017-03-22 22:00:00",
        "level": "0"
      },
      {
        "count": 5,
        "create_time": "2017-03-22 22:00:00",
        "level": "2"
      },
      {
        "count": 5,
        "create_time": "2017-03-22 23:00:00",
        "level": "0"
      },
      {
        "count": 0,
        "create_time": "2017-03-22 23:00:00",
        "level": "1"
      },
      {
        "count": 5,
        "create_time": "2017-03-22 23:00:00",
        "level": "2"
      }]
    
    import time
    
    ls.sort(key = lambda x: time.strptime(x["create_time"], "%Y-%m-%d %H:%M:%S"))
    
    ret = filter(lambda x: x['create_time'] == ls[-1]['create_time'], ls)
    
    print ret
    """
    [{'count': 5, 'create_time': '2017-03-22 23:00:00', 'level': '0'}, {'count': 0, 'create_time': '2017-03-22 23:00:00', 'level': '1'}, {'count': 5, 'create_time': '2017-03-22 23:00:00', 'level': '2'}]
    """

    回复
    0
  • 取消回复