合并列表中具有相同值的两个或多个对象

Merge two or more objects with the same value in list

我想合并列表中两个或多个具有相同 momentenum 值的对象,并将 value 添加到我们自己。如果我写一个例子会更好:

输入:

[Credit(value=111, moment=<CreditMoment.APP: 'APP'>), Credit(fee_value=222, moment=<CreditMoment.APP: 'APP'>), Credit(value=444, moment=<CreditMoment.OFFER: 'OFFER'>)]

预期结果:

[Credit(value=333, moment=<CreditMoment.APP: 'APP'>), Credit(value=444, moment=<CreditMoment.OFFER: 'OFFER'>)]

正如您现在看到的,预期列表有 2 个元素,第一个元素合并了 value=333

元素来自这个class:

class CreditMoment(str, AutoNameEnum):
    APP= auto()
    OFFER = auto()
    COMPLETION = auto()

这样的事情会有所帮助。

dic = {}
for credit in lis:
    # Will create a dict that willh have moment value as key and sum all the values
    dic[credit.moment.value] = dic.get(credit.moment.value, 0) + credit.value

# Now recreate the list

[Credit(value=v, moment=x) for x,v in dic.items()]