简体   繁体   中英

Summing repeated elements of list of tuples

Let's say I have a list of tuples like

[('a', 1), ('a', 1), ('a', 1), ('b', 2), ('e', 3), ('e', 3), ('g', 4), ('b', 1)]

How might I get a list of tuples like

[('a', 3), ('b', 3), ('e', 6), ('g', 4)]

where repeated elements have the values following the comma summed and this summed value is placed after the now unique element in a new list of tuples.

You can use a dictionary and dict.get(letter, 0) to sum the values per letter, then output the dict as a list of tuples.

data = [('a', 1), ('a', 1), ('a', 1), ('b', 2), ('e', 3), ('e', 3), ('g', 4), ('b', 1)]

def combine(data):
    output = {}
    for letter, number in data:
        output[letter] = output.get(letter, 0) + number
    return list(output.items())

print(combine(data))
#[('a', 3), ('b', 3), ('e', 6), ('g', 4)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM