Is there any pythonic way to find average of specific tuple elements in array?(有没有任何pythonic方法可以找到数组中特定元组元素的平均值?)
问题描述
我想把这段代码写成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 的起始值设置为 float 值 0.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)
这篇关于有没有任何pythonic方法可以找到数组中特定元组元素的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有任何pythonic方法可以找到数组中特定元组元素的平均值?
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
