def regroup(values): groups = dict() for d in values: key = (d["prod_name"], d["prod_hola"]) if key in groups: group = groups[key] group["rashod"] += d["rashod"] group["prihod"] += d["prihod"] else: groups[key] = d.copy() return list(groups.values())
还有一个更通用的解决方案:
def generic_regroup(values, keys): groups = dict() valkeys = [k for k in values[0] if k not in key] for d in values: key = tuple(d[k] for k in keys) if key in groups: group = groups[key] for k in valkeys: group[k] += d[k] else: groups[key] = d.copy() return list(groups.values())results = generic_regroup(values, ("prod_name", "prod_hola"))
现在肯定有人会采用涉及itertools的更聪明的解决方案…
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)