[英]write a function which accepts a list of tuple objects and returns a dictionary containing the sum of values of all the strings
Continue from the previous question, write a function called get_sum(tuple_list) which accepts a list of tuple objects and returns a dictionary containing the sum of values of all the strings that appear in the list. 从上一个问题继续,编写一个名为get_sum(tuple_list)的函数,该函数接受元组对象的列表,并返回一个包含该列表中所有字符串的值之和的字典。 For example, if we have the following data (a list of tuple objects):
例如,如果我们具有以下数据(元组对象列表):
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)] tuple_list = [('a',5),('a',5),('b',6),('b',4),('b',3),('b',7) ]
then the dictionary should contain the following: 那么字典应包含以下内容:
{'a': 10, 'b': 20} My problem is how to distinguish ab value when sum them together {'a':10,'b':20}我的问题是将它们加在一起时如何区分ab值
Test 测试
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
sum_dict = get_sum(tuple_list)
for key in sorted(sum_dict.keys()):
print("{}: {}".format(key, sum_dict[key]))
Result a: 10 b: 20 结果a:10 b:20
I would suggest to use defauldict
. 我建议使用
defauldict
。 You can use a normal dict
but it will take some more if
statements. 您可以使用普通
dict
但if
语句会花费更多。
from collections import defaultdict
d = defaultdict(int)
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
for a,b in tuple_list:
d[a] +=b
print (d)
#defaultdict(<class 'int'>, {'a': 10, 'b': 20})
If you want to use your original method, you can use tuple unpacking: 如果要使用原始方法,则可以使用元组拆包:
def get_sum(l):
new_dict = {}
for x, y in l:
if x not in new_dict:
new_dict[x] = y
else:
new_dict[x] +=y
return new_dict
print (get_sum(tuple_list))
#{'a': 10, 'b': 20}
A very simple solution using the standard dict 'get' method: 使用标准dict'get'方法的非常简单的解决方案:
d={}
for c,v in tuple_list:
d[c]=d.get(c,0)+v
Try this out: 试试看:
def get_sum(tuple_list):
new_dict = {}
for tuple in tuple_list:
if tuple[0] not in new_dict:
new_dict[tuple[0]] = tuple[1]
else:
new_dict[tuple[0]] += tuple[1]
return new_dict
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
sum_dict = get_sum(tuple_list)
for key in sorted(sum_dict.keys()):
print("{}: {}".format(key, sum_dict[key]))
If the entry is not in your list, then you make the dictionary key, value pair be the first and second indexes of the tuple. 如果该条目不在列表中,则您将字典键设为键,值对是元组的第一和第二索引。 Otherwise, the key is already in the dictionary, so we simply add to its current value.
否则,键已在字典中,因此我们只需将其添加到当前值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.