我有一个需要分组的字典列表,我需要同时进行计数和求和。计算这本字典在我的情况下为工人出现的次数,以及根据工人我可以同时执行一个键的总和字段的 SUM 是多少,但不能同时执行。
这是我的代码
grouper = lambda x: (x["rw_worker_nick"], x["rw_date"].replace(day=1))
vacation_group = []
for key, grp in groupby(sorted(vacation, key = grouper), grouper):
temp_dict = dict(zip(["rw_worker_nick", "rw_date"], key))
temp_dict['vac_days'] = len(list(grp))
temp_dict['vac_duration'] = sum(item["rw_duration"] for item in grp)
vacation_group.append(temp_dict)
总和始终返回 0
有什么建议么 ??
谢谢你
您不能迭代groupby
产生多次的可迭代对象。list(grp)
消耗了迭代中的所有项目。
首先存储列表,然后从中获取长度和总和:
for key, grp in groupby(sorted(vacation, key = grouper), grouper):
temp_dict = dict(zip(["rw_worker_nick", "rw_date"], key))
grp = list(grp))
temp_dict['vac_days'] = len(grp)
temp_dict['vac_duration'] = sum(item["rw_duration"] for item in grp)
vacation_group.append(temp_dict)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句