Python 在不使用 .values() 等的情况下查找字典中值的均值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22416450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:55:38  来源:igfitidea点击:

Finding mean of a values in a dictionary without using .values() etc

python

提问by Rachel

I have a dictionary that looks like:

我有一本字典,看起来像:

G={'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}

I have to find the mean of the values e.g. mean(18,17,19,15,0) using a simple forloop without using built in functions like .values(), .items()and so on. I tried the following but am getting an error:

我必须使用一个简单的for循环而不使用诸如.values(),.items()等内置函数来找到值的平均值,例如 mean(18,17,19,15,0) 。我尝试了以下操作,但出现错误:

d=[float(sum(values)) / len(values) for key, values in G]
    return (d)   
ValueError: need more than 1 value to unpack

Can someone help me fix this????

有人可以帮我解决这个问题吗????

采纳答案by Aaron Hall

To do this with a "simple for loop", using your constraints against using the dict methods:

要使用“简单的 for 循环”执行此操作,请使用您的约束而不是使用 dict 方法:

G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}


count = 0
_sum = 0
for key in G:
    count += 1
    _sum += G[key]

print('this is the mean: ', _sum/count)

If you're supposed to avoid dict methods, clearly this is an academic exercise.

如果你应该避免使用 dict 方法,显然这是一个学术练习。

Without that constraint:

没有这个限制:

The statisticsmodule in the standard library has a meanmethod, which would be my first thought (as the standard library does not require third party packages.):

statistics标准库中的模块有一个mean方法,这是我的第一个想法(因为标准库不需要第三方包。):

>>> G={'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
>>> from statistics import mean
>>> mean(G[k] for k in G)
13.8

Third party packages like numpy and pandas have objects with a meanmethod:

像 numpy 和 pandas 这样的第三方包有一个带有mean方法的对象:

>>> from numpy import array
>>> array([G[k] for k in G]).mean()
13.8

>>> from pandas import Series
>>> Series([G[k] for k in G]).mean()
13.8

If we allow ourselves to use the values()method, this gets a little simpler with iterable unpacking. For some reason the other answers violate that condition, so I figure I should show the more efficient way of doing it:

如果我们允许自己使用该values()方法,通过可迭代解包,这会变得更简单一些。出于某种原因,其他答案违反了该条件,所以我想我应该展示更有效的方法:

>>> Series([*G.values()]).mean()
13.8

回答by Gian

Iteration over a dictionary iterates over its keys. Try just using for key in G, and then using G[key]appropriately instead of values.

对字典的迭代会对其键进行迭代。尝试只使用for key in G, 然后G[key]适当地使用而不是values

Alternatively, use the iteritems()method of the dictionary to get key, valuepairs from G, i.e.:

或者,使用iteritems()字典的方法key, value从G中获取对,即:

d=[float(sum(values)) / len(values) for key, values in G.iteritems()]

(For the record, your actual method of computing a mean doesn't look right to me, but you may as well fix the iteration problem first).

(为了记录,您计算均值的实际方法在我看来并不正确,但您最好先解决迭代问题)。

回答by ebarr

You want:

你要:

mean = sum([G[key] for key in G])/float(len(G))

Your original code will also produce a:

您的原始代码还将产生:

TypeError: 'int' object is not iterable

when you try to sum the values.

当您尝试对值求和时。

回答by Gassa

Use G.values()to get all the values from a dictionary.

用于G.values()从字典中获取所有值。

G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}
d = float(sum(G.values())) / len(G)
print (d)

This prints 13.8.

这打印13.8.

Note that there is a difference between Python 2 and Python 3 here. In Python 2, G.values()is a newly constructed list of values. In Python 3, it is a generator, which can be thought of as a “lazy list”. The same thing is called G.itervalues()in Python 2.

请注意,此处 Python 2 和 Python 3 之间存在差异。在 Python 2 中,G.values()是一个新构造的值列表。在 Python 3 中,它是一个生成器,可以被认为是一个“惰性列表”。同样的事情G.itervalues()在 Python 2 中被调用。

回答by barrios

In Python 3.4 upwards there is a very clear way:

在 Python 3.4 以上有一个非常明确的方法:

import statistics
numbers = [G[key] for key in G]
mean_ = statistics.mean(numbers)

回答by Jerome Montino

Another for-loop, this one not needing a counter for items.

另一个 for 循环,这个循环不需要物品的计数器。

G = {'E': 18.0, 'D': 17.0, 'C': 19.0, 'B': 15.0, 'A': 0}

sum = 0
for k in G:
    sum += float(G[k])

print "Mean: " + str(sum/len(G))

Results to:

结果:

Mean: 13.8
[Finished in 0.3s]

Actually, given your data, there's no need to use float. On my end, removing floatand just leaving sum += G[k]still outputs the same since the values are not strings anyway.

实际上,鉴于您的数据,没有必要使用float. 最后,删除float和离开sum += G[k]仍然输出相同,因为值无论如何都不是字符串。

回答by Adam Erickson

What I suggest instead of the current answers is adopting a functional programming paradigm that is reusable and flexible. For example, creating a function to calculate any statistic on listvalues contained within a simple dict:

我建议采用一种可重用且灵活的函数式编程范式,而不是当前的答案。例如,创建一个函数来计算listsimple 中包含的值的任何统计信息dict

def summarize_dict(dictionary, function):
        dict_new = {}
    for k,v in dictionary.items():
        dict_new[k] = function(v)
    return dict_new

Testing:

测试:

import numpy as np

keys = ["a","b","c","d","e"]
values = [range(2),range(4),range(6),range(8),range(10)]
dictionary = dict(zip(keys, values))

summarize_dict(dictionary, np.mean)

Yields:

产量:

{'a': 0.5, 'b': 1.5, 'c': 2.5, 'd': 3.5, 'e': 4.5}

回答by Sergio R

If you use numpy:

如果您使用 numpy:

import numpy as np

np.array(list(dict.values())).mean()

回答by insanely_sin

import numpy as np
np.mean(list(dict.values()))