python - 如何在 python 中对 namedtuple 使用 sum()/average()?

标签 python numpy namedtuple

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
points = [Point(x=1.0, y=1.0), Point(x=2.0, y=2.0)] 

我想计算 points 列表的平均点数,即接收 Point(1.5, 1.5) 作为结果:

point = average(points) # x = 1.5, y = 1.5

例如我知道 np.average(points, axis=0) 如果 points.shape(N, 2),但我宁愿保留一个命名的元组。

最佳答案

计算平均坐标:

import numpy as np
Point(np.average([p.x for p in points]),
      np.average([p.y for p in points]))
#Point(x=1.5, y=1.5)

或者,更好的是,将点列表隐式转换为 numpy 数组,获取平均值,然后将结果转换回点

Point(*np.average(points, axis=0))
#Point(x=1.5, y=1.5)

关于python - 如何在 python 中对 namedtuple 使用 sum()/average()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401260/

相关文章:

python - 无法在树莓派上为python3.4安装urllib3

Python 瓶颈;确定文件比较功能的最佳 block 大小

python - 在 Python 中使用正则表达式匹配输入

python - 从 .csv 文件中读取值并将它们转换为 float 组

python - 从 numpy 数组在 matplotlib 中显示多个图像

python - 从命名元组列表中写入 numpy.array()

python - 计算 OOZIE 时间戳差异的最佳方法是什么?

python - 使用 numpy 将棕褐色效果应用于 3D 数组

python - 我怎样才能从 Python 的 namedtuple 获得降序的 OrderedDict?

python - 无法初始化子类命名元组的实例