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

Şev*_*man 23 python arrays tuples average python-3.x

我想将此代码编写为pythonic。我的实际数组比此示例大得多。

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

print(np.mean(array,key = lambda x:x [1]))TypeError:mean()得到了意外的关键字参数'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]))
Run Code Online (Sandbox Code Playgroud)

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

我正在使用Python 3.7

Pet*_*ood 27

如果您使用的是Python 3.4或更高版本,则可以使用以下statistics模块:

from statistics import mean

average = mean(value[1] for value in array)
Run Code Online (Sandbox Code Playgroud)

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

average = sum(value[1] for value in array) / len(array)
Run Code Online (Sandbox Code Playgroud)

这些解决方案都使用Python的一个不错的功能,称为生成器表达式。循环

value[1] for value in array
Run Code Online (Sandbox Code Playgroud)

及时且高效地创建新序列。参见PEP 289-生成器表达式

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

>>> 25 / 4
6

>>> 25 / float(4)
6.25
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

  • 我想说,“ float”强制转换方式比为“ sum”传递一个怪异的“ 0.0”值参数要容易得多。 (5认同)