简体   繁体   English

编写一个接受元组对象列表并返回包含所有字符串值之和的字典的函数

[英]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. 您可以使用普通dictif语句会花费更多。

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.

相关问题 如何编写一个 function 接受两个元组,并返回所有整数按升序出现的合并元组? - How to write a function that accepts two tuples, and returns the merged tuple in which all integers appears in ascending order? Pandas AssertionError 应用 function 时返回包含列表的元组 - Pandas AssertionError when applying function which returns tuple containing list 如何在python中编写一个接受字典列表并返回新字符串列表的函数 - how to write a function in python that accepts a list of dictionaries and returns a new list of strings 我如何编写一个程序,将字符串列表作为输入并返回一个字典,其中包含匹配字符串的单词索引 - how do I write a program that takes a list of strings as input and returns a dictionary, containing an index of the words to the matching strings 具有相同值的元组列表的总和并转换为字典 - Sum of List of tuple with same values and convert to dictionary 一个 function 接受一个列表并返回一个包含列表中所有其他项目的列表 - a function that accepts a list and returns a list containing every other item in the list 编写一个函数accumulate_product,该函数接受一个列表作为参数,并返回列表中所有非零数字的乘积 - Write a function accumulate_product that accepts one list as a parameter and returns the product of all the numbers in the list that are not zeros 如何用列表中的每个字典的元组替换字典值 - How to replace dictionary values which is dictionary with tuple for each dictionary in list 在python 3中编写一个接受两个字符串并返回True的函数 - Writing a function which accepts two strings and returns True in python 3 python函数返回包含值的字典以及原始字典中具有该值的键的对应列表 - python function Returns a dictionary containing values along with a corresponding list of keys that had that value from the original dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM