简体   繁体   English

谁能帮我找到字典python 2.7的平均值?

[英]Can anyone help me with finding the average of dictionary python 2.7?

I am having problems iterating over my dictionary. 我在遍历字典时遇到问题。 The program should print the average of the numbers beside each name in the dictionary. 该程序应在字典中每个名称旁边打印数字的平均值。 Can anyone help me figure it out what I'm doing wrong? 谁能帮我弄清楚我在做什么错? The following is my current code: 以下是我当前的代码:

guest={"Mary":"15", "Joe":"13", "Dustin":"12"}

def CalcAverage(guest):
    total = 0.0
    numPersons = 0
    for key,value in guest.items():
        numPersons += len(guest[key])
        total = float(sum(guest[value]))
    return total/numPersons

print CalcAverage(guest)

What you are doing wrong: 您做错了什么:

  1. key and value already contain the key and value from the dictionary. keyvalue已经包含字典中的键和值。 There is no need to access the dictionary again as in guest[key] . 无需像guest[key]那样再次访问字典。
  2. numPersons should be incremented by 1 on each iteration of the loop, not by the length of the value which is what len(guest[key]) does. numPersons应该在循环的每次迭代中增加1,而不是len(guest[key])的值的长度增加。
  3. total should accumulate the total of the values, not be assigned to each one, ie total += float(value) . total应该累积值的总数,而不是分配给每个值,即total += float(value)

Correcting those 3 items yields code like this: 纠正这3个项目将产生如下代码:

guest= {"Mary":"15", "Joe":"13", "Dustin":"12"}

def CalcAverage(guest):
    total = 0.0
    numPersons = 0
    for key, value in guest.items():
        numPersons += 1
        total += float(value)
    return total / numPersons

>>> CalcAverage(guest)
13.333333333333334

You can simplify this by using a generator expression to convert each value to a float, sum those floats, then divide by the number of items in the guest dictionary: 您可以通过使用生成器表达式将每个值转换为浮点数,将这些浮点数相加,然后除以来宾字典中的项数,来简化此操作:

def CalcAverage(guest):
    return sum(float(v) for v in guest.values()) / len(guest)

>>> CalcAverage(guest)
13.333333333333334

You have been defining your numbers a strings, which makes them less easy to handle. 您一直在为数字定义一个字符串,这使得它们不那么容易使用。 Better would be: 更好的是:

guest={"Mary": 15, "Joe": 13, "Dustin": 12}

Or as floats already: 或者已经是浮点数了:

guest={"Mary": 15.0, "Joe": 13.0, "Dustin": 12.0}

Also you used float(sum(guest[value]) which has two major issues: 此外,您还使用了float(sum(guest[value]) ,它有两个主要问题:

  • guest[value] tries to get the value with the key stored in value from the dictionary. guest[value]尝试从字典中获取具有存储在value的键的value But value is no key, that can't work. 但是value不是关键,那是行不通的。
  • You are having string values only, you can't sum them with sum() . 您只有字符串值,不能用sum()

There are many other problems in the code, some examples: 代码中还有许多其他问题,例如:

  • for key,value in guest.items(): makes the key and they value avaible as key and value in the for block. for key,value in guest.items():使该key及其value在for块中可用作keyvalue You don't need to index guest later. 您以后无需为guest建立索引。 That means that guest[key] is the same as value . 这意味着guest[key]value相同。
  • len(guest[key]) would return the length of value , which is a number and would return 2 (all your number strings have two digits). len(guest[key])将返回value的长度,该长度是一个数字,并且将返回2 (所有数字字符串都有两位数字)。

What you want to archive can be done much more easy: 您想要存档的内容可以更轻松地完成:

def calc_average(guest)
    length = len(guest)
    values = [float(value) for value in guest.values()]
    return sum(values) / length

The first line gets the length of the dictionary. 第一行获取字典的长度。 The second line pull all values from the list and converts them to floats. 第二行从列表中提取所有值,并将它们转换为浮点数。 This is a list comprehension. 这是一个列表理解。 The last line sums the values and returns the average. 最后一行将这些值相加并返回平均值。 BTW: I also adapted the name of the function to the usual Python naming convention for functions. 顺便说一句:我还根据通常的Python函数命名约定对函数的名称进行了修改。

Value is a str type you can convert into float and simple increment to total 值是一个str类型,您可以将其转换为float并简单将其累加为total

def CalcAverage(guest):
total = 0.0
for key, value in guest.items():
    total += float(value)
return total / len(guest)

print CalcAverage(guest)

You can use The reduce is in the functools in Python 3.0. 您可以在Python 3.0的functools中使用reduce。 It is more complex. 比较复杂。 It accepts an iterator to process, but it's not an iterator itself. 它接受要处理的迭代器,但它本身不是迭代器。 It returns a single result 它返回一个结果

def CalcAverage(guest):
    total = 0.0
    total = reduce(lambda x, y: float(x) + float(y), guest.values())
    return total / len(guest)

print CalcAverage(guest)

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

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