有没有任何pythonic方法可以找到数组中特定元组元素的平均值?

2022-01-20 00:00:00 python python-3.x arrays average tuples

问题描述

我想把这段代码写成pythonic.我的真实数组比这个例子大得多.

I want to write this code as pythonic. My real array much bigger than this example.

(5+10+20+3+2)/5

( 5+10+20+3+2 ) / 5

print(np.mean(array,key=lambda x:x[1]))TypeError: mean() 得到了一个意外的关键字参数 'key'

print(np.mean(array,key=lambda x:x[1])) TypeError: mean() got an unexpected keyword argument 'key'

array = [('a', 5) , ('b', 10), ('c', 20), ('d', 3), ('e', 2)]

sum = 0
for i in range(len(array)):
    sum = sum + array[i][1]

average = sum / len(array)
print(average)

import numpy as np
print(np.mean(array,key=lambda x:x[1]))

如何避免这种情况?我想用第二个例子.

How can avoid this? I want to use second example.

我正在使用 Python 3.7

I'm using Python 3.7


解决方案

如果你使用 Python 3.4 或以上版本,你可以使用 statistics 模块:

If you are using Python 3.4 or above, you could use the statistics module:

from statistics import mean

average = mean(value[1] for value in array)

或者,如果您使用的 Python 版本早于 3.4:

Or if you're using a version of Python older than 3.4:

average = sum(value[1] for value in array) / len(array)

这些解决方案都使用了 Python 的一个很好的特性,称为生成器表达式.循环

These solutions both use a nice feature of Python called a generator expression. The loop

value[1] for value in array

以一种及时且高效的方式创建一个新序列.请参阅 PEP 289 -- 生成器表达式.

creates a new sequence in a timely and memory efficient manner. See PEP 289 -- Generator Expressions.

如果您使用的是 Python 2,并且您正在对整数求和,我们将进行整数除法,这将截断结果,例如:

If you're using Python 2, and you're summing integers, we will have integer division, which will truncate the result, e.g:

>>> 25 / 4
6

>>> 25 / float(4)
6.25

为了确保我们没有整数除法,我们可以将 sum 的起始值设置为 float0.0.但是,这也意味着我们必须用括号明确生成器表达式,否则会出现语法错误,并且不太美观,如评论中所述:

To ensure we don't have integer division we could set the starting value of sum to be the float value 0.0. However, this also means we have to make the generator expression explicit with parentheses, otherwise it's a syntax error, and it's less pretty, as noted in the comments:

average = sum((value[1] for value in array), 0.0) / len(array)

最好使用 fsum 来自 math 模块将返回一个 float:

It's probably best to use fsum from the math module which will return a float:

from math import fsum

average = fsum(value[1] for value in array) / len(array)

相关文章