[英]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.您可以使用字典和
dict.get(letter, 0)
对每个字母的值求和,然后将 output dict
作为元组列表。
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.