繁体   English   中英

使用公共 id 从字典中获取键值的总和并获取最大日期

[英]Get sum of key values and get max date from a dictionary using a common id

你好我有一个这样的字典数组 -

[{'id':'450', 'marks':'30', 'end_date':datetime.datetime(2021, 2, 3, 0, 0, tzinfo=<UTC>)},
 {'id':'450', 'marks':'60', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)},
 {'id':'450', 'marks':'80', 'end_date':None},
 {'id':'452', 'marks':'51', 'end_date':datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<UTC>)},
 {'id':'452', 'marks':'27', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}]

我想获得常见 ID 的标记总和和最大日期。 对于上述数据,我的 output 应该看起来像 -

[{'id':'450', 'marks':'170', 'end_date':datetime.datetime(2021, 2, 7, 0, 0, tzinfo=<UTC>)},
 {'id':'452', 'marks':'78', 'end_date':datetime.datetime(2021, 3, 3, 0, 0, tzinfo=<UTC>)}]

我尝试使用counter ,但它也给了我 id 的总和。

您可以使用itertools.groupby将键组合在一起,然后执行必要的操作( maxsum )。

ll.sort(key=lambda x: x["id"])
result = []
for key, group in itertools.groupby(ll, key=lambda x: x["id"]):
    group = list(group)
    result.append(
        {
            "id": key,
            "marks": sum(int(g["marks"]) for g in group),
            "end_date": max(g["end_date"] for g in group if g["end_date"]),
        }
    )


print(result)

Output

[{'id': '450', 'marks': 170, 'end_date': datetime.datetime(2021, 2, 7, 0, 0)}, {'id': '452', 'marks': 78, 'end_date': datetime.datetime(2021, 3, 3, 0, 0)}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM