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)
,但是我宁愿保留一个命名的元组。
答案 0 :(得分: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
Point(*np.average(points, axis=0))
#Point(x=1.5, y=1.5)
答案 1 :(得分:1)
也许我错过了一些东西,但是如果您想避免使用numpy
,那么可以
>>> Point(sum(p.x for p in points)/len(points),sum(p.y for p in points)/len(points))
Point(x=1.5, y=1.5)
不过似乎有点回旋处。
答案 2 :(得分:0)
这是namedtuple
的新子类,它具有一个classmethod
,可以根据点序列的平均值或总和构造一个新点。
from collections import namedtuple
class Point(namedtuple('Point', ['x', 'y'])):
@classmethod
def from_average(cls, points):
from_sum = cls.from_sum(points)
return cls(from_sum.x / len(points), from_sum.y / len(points))
@classmethod
def from_sum(cls, points):
if not all(isinstance(p, cls) for p in points):
raise ValueError('All items in sequence must be of type {}'.format(cls.__name__))
x = sum(p.x for p in points)
y = sum(p.y for p in points)
return cls(x, y)
point_1 = Point(1.0, 1.0)
point_2 = Point(2.0, 2.0)
point_3 = Point.from_average([point_1, point_2])
point_3
# Point(x=1.5, y=1.5)
point_4 = Point.from_sum([point_1, point_2])
point_4
# Point(x=3.0, y=3.0)
答案 3 :(得分:0)
这是一种可爱的方式,仅使用Python内置程序:
In [1]: from collections import namedtuple
...: Point = namedtuple('Point', ['x', 'y'])
...: points = [Point(x=1.0, y=1.0), Point(x=2.0, y=2.0)]
...:
In [2]: import statistics
In [3]: Point(*map(statistics.mean, zip(*points)))
Out[3]: Point(x=1.5, y=1.5)
为什么从一开始就使用numpy
?这里没有多大意义。