简体   繁体   English

您如何找到字典的平均值?

[英]How do you find the average of a dictionary?

So let's say I have this dictionary 假设我有这本字典

{'Taylor Swift': ['Kanye West']}

I would expect 1.0 from this as there is one value (which is 'Kanye West') divided by one key (which is 'Taylor Swift') to get the average of 1.0. 我希望从中获得1.0,因为只有一个值(即“ Kanye West”)除以一个键(即“ Taylor Swift”)才能得到1.0的平均值。

And let's say I have this dictionary 假设我有这本字典

{'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}

I would expect the average of 2.0 from this as there are 4 values divided by 2 keys. 我希望从中得到2.0的平均值,因为有4个值除以2个键。

This is the code I have tried: 这是我尝试过的代码:

average = 0
sum = 0
for n in data:
    sum = sum + n
average = sum / len(data)

I have tried many other ways too through online search and the common error I get is this: 我也通过在线搜索尝试了许多其他方式,而我遇到的常见错误是:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Taking "average" as "the average number of items in the lists", you can achieve it as: 将“平均值”作为“列表中的平均项目数”,可以实现为:

average_length = sum( len(v) for v in data.values() ) / len(data)

The first part adds together the length of all the lists you have as dictionary values, while len(data) is the number of key:value pair you have in the dictionary. 第一部分将您拥有的所有列表的长度加在一起作为字典值,而len(data)是您在字典中具有的key:value对的数量。

Try this 尝试这个

average = 0
sum = 0
for key in data.keys():
    sum = sum +len(data[key])
average = sum / len(data)
 average = 0
 sum = 0
 for v in data.values():
      sum = sum + len(v)

 average = sum / len(data.keys())

Use simple for loop 使用简单的for循环

var= {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': 
['Johnny Depp', 'Tom Hanks']}

sum = 0
for value in var.values():
    sum = len(value)+sum

Average = sum/len(var)
print(Average)

Output 输出量

2.0

Could use reduce here too: 也可以在这里使用减少:

from functools import reduce
data = {'Taylor Swift': ['Kanye West', 'Elvis Presley'], 'Adam Sandler': ['Johnny Depp', 'Tom Hanks']}
reduce((lambda x, y: len(x)+len(y)), data .values()) / len(data )

Get the length of values first and divide it by the length of keys. 首先获取值的长度,然后除以键的长度。

sum(len(i) for i in data.values())/float(len(data.keys()))

and this gives the same result as well, 这也带来了相同的结果,

sum(len(i) for i in x.values())/float(len(x))

Here you go 干得好

#some dictionary
d={'Taylor Swift': ['Kanye',' West', 'Elvis',' Presley','l'], 'Adam Sandler': ['Johnny',' Depp', 'Tom',' Hanks']}
#Sum function gets the sum of all values in dictionary
#Len function gets the total number of keys in dictionary
#Multiplying with 1.0 to get exact division, else import division function from _future_ library 
avg = sum(len(v) for v in d.itervalues())*1.0/len(d)
print avg 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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