[('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)]
例如,我有上面的元组列表,如何找到重复项(即“ Visa”)并求和它们的值(即980.5 + 215.0)?输出应为:
[('Visa', 1195.5), ('Rogers', 61.5)]
使用字典:
>>> data = [('Visa', 980.5), ('Rogers', 61.5), ('Visa', 215.0)] >>> result = {} >>> for card, value in data: total = result.get(card, 0) + value result[card] = total >>> print result.items() [('Visa': 1195.5), ('Rogers': 61.5)]