PR

Pythonで複数の座標の平均を求める関数

Python Python
Python

複数の座標の平均を求める関数を作ってみました。
正方形の中心座標などを求めることができます。

# 複数の座標の平均を求める
def meanPoint(points):
	if len(points) == 0:
		return {"x": 0, "y": 0}
	x = 0
	y = 0
	for point in points:
		x = x + point["x"]
		y = y + point["y"]
	x = x / len(points)
	y = y / len(points)
	return {"x": x, "y": y}

実際に動かしてみます。

# -*- coding: utf-8
import json

points = []
points.append({"x": 2, "y": 10})
points.append({"x": 4, "y": 10})
points.append({"x": 4, "y": 5})
points.append({"x": 6, "y": 5})
# 複数の座標の平均を求める
print("複数の座標の平均を求める")
print(json.dumps(meanPoint(points), indent=4))
複数の座標の平均を求める
{
    "x": 4.0,
    "y": 7.5
}
タイトルとURLをコピーしました