python 字典比较
大家讲道理
大家讲道理 2017-04-18 10:29:04
0
3
584

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

    [{
    "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"
      }]
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

répondre à tous(3)
Ty80

Changez la somme au maximum dans la dernière question :

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

Des problèmes comme celui-ci peuvent être résolus en utilisant 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
巴扎黑

L'idée est de trier d'abord puis de filtrer

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'}]
"""
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal