[英]Return the sum of all values in a dictionary Python
need help making the function sumcounts(D) where D is a dictionary with numbers as values, returns the sum of all the values. 需要帮助制作函数sumcounts(D)其中D是一个以数字作为值的字典,返回所有值的总和。 Sample output should be like this:
示例输出应如下所示:
>>> sumcounts({"a":2.5, "b":7.5, "c":100})
110.0
>>> sumcounts({ })
0
>>> sumcounts(strcount("a a a b"))
4
It's already there: 它已经存在:
sum(d.values())
Or maybe that: 或许那样:
def sumcount(d):
return sum(d.values())
I'm not sure what you've been taught about dictionaries, so I'll assume the bare minimum. 我不确定你对字典学过什么,所以我会假设最低限度。
total
variable and set it to 0
. total
变量并将其设置为0
。 for x in y
syntax. for x in y
语法的法线迭代字典中的所有键。 your_dict[key_name]
. your_dict[key_name]
从字典中获取其各自的值。 total
. total
。 Michael already posted the regular Pythonic solution. 迈克尔已经发布了常规的Pythonic解决方案。
The answer as given by Michael above is spot on! 迈克尔上面给出的答案就是现场!
I want to suggest that if you are going to work with large data sets to look at the most excellent Pandas Python Framework.(Maybe overkill for your problem but worth a look) 我想建议,如果你打算使用大型数据集来查看最优秀的Pandas Python框架。(也许你的问题有点过分但值得一看)
It accepts dictionaries and transforms it into a data set, for instance 例如,它接受字典并将其转换为数据集
yourdict = {"a":2.5, "b":7.5, "c":100}
dataframe = pandas.Series(yourdict)
You now have a very powerfull data frame that you can realy do a lot of neat stuff on including getting the sum 你现在有一个非常强大的数据框架,你可以真正做很多整洁的东西,包括获得总和
sum = dateframe.sum()
You can also easily plot it, save it to excel, CSV, get the mean, standard deviation etc... 您也可以轻松地绘制它,将其保存为excel,CSV,获得均值,标准差等...
dateframe.plot() # plots is in matplotlib
dateframe.mean() # gets the mean
dateframe.std() # gets the standard deviation
dataframe.to_csv('name.csv') # writes to csv file
I can realy recomend Pandas. 我真的可以推荐熊猫。 It changed the way I do data business with Python...It compares well with the R data frame by the way.
它改变了我使用Python进行数据业务的方式......顺便说一句,它与R数据框架相比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.