更新时间:2023-01-31 07:37:08
这是使用纯Python的解决方案.
Here's a solution with plain python.
dlst = [{"id":1, "symbol":'A', "num":4}, {"id":2, "symbol":'A', "num":3},
{"id":1, "symbol":'A', "num":5}, {"id":2, "symbol":'B', "num":1}]
# Create a dict where keys are tuples of (id,symbol), values are num
combined_d = {}
for d in dlst:
id_sym = (d["id"], d["symbol"])
if id_sym in combined_d:
combined_d[id_sym] += d["num"]
else:
combined_d[id_sym] = d["num"]
# create a list of dictionaries from the tuple-keyed dict
result = []
for k, v in combined_d.items():
d = {"id": k[0], "symbol": k[1], "num": v}
result.append(d)
print(result)
它可以做您想要的,但是结果列表没有排序,因为它是根据字典构建的.
It does what you want, but the resulting list is not sorted, as it's built from a dictionary.