一个列表当中有一个日期的值,我想求这个日期里面当天最大时间的那一条,大神们如何写呢?
原始列表
`
[{
"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"
}]
PHP中文网2017-04-18 10:31:04
Change sum to max in the last 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]
PHPz2017-04-18 10:31:04
Problems like this can be solved using 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
巴扎黑2017-04-18 10:31:04
The idea is to sort first and then filter
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'}]
"""