首页 > 解决方案 > 如何计算无限数量的坐标输入的平均值?

问题描述

我正在尝试编写一个代码来找到地球上多个位置的中点。我用3个坐标写了一个,但我想让它无限。

如果输入只是一个普通整数或浮点数,那么很容易找到它们的平均值,但是坐标用逗号分隔,在计算它们的平均值之前,您必须分开并取纬度和经度。这就是让它变得困难的事实。

这是带有“3”坐标的代码:

cord_1 = input("Enter the Coordinates of First Point:")
cord_2 = input("Enter the Coordinates of Second Point:")
cord_3 = input("Enter the Coordinates of Third Point:")

c11 = float(cord_1.partition(",")[0])   
c12 = float(cord_1.partition(",")[-1])

c21 = float(cord_2.partition(",")[0])
c22 = float(cord_2.partition(",")[-1])   #These 6 lines seperates the coordinates by before comma and after comma,
                                         # (Which means longitude and latitude)
c31 = float(cord_3.partition(",")[0])
c32 = float(cord_3.partition(",")[-1])

mid_lon = str("{:.6f}".format(float((c11 + c21 + c31)/3)))   #These lines takes first 6 digits of average coordinate, NOT ROUND IT   
mid_lat = str("{:.6f}".format(float((c12 + c22 + c32)/3)))

print(mid_lon, mid_lat, sep =", ")                           #Reunions the latitude and longitude and prints it

输出:

Enter the Coordinats of First Point: 38.911203, 27.832993
Enter the Coordinats of Second Point: 38.916983, 27.819857
Enter the Coordinats of Third Point: 38.914627, 27.836506
38.914271, 27.829785

我写的代码可能是解决问题的死方法,我当然愿意接受更智能的解决方案。

标签: pythoncoordinates

解决方案


使用循环输入坐标,就像这样。

请注意,彼此相距很远的坐标(尤其是在全球范围内)会在这里给你错误的结果,但输入阶段仍然很好。

# Input coordinates into a list

coords = []
while True:
    try:
        i = input(f"Enter the Coordinates of Point {len(coords) + 1}:").strip()
        if not i:  # An empty string breaks the loop
            break
        lon, _, lat = i.partition(",")
        coords.append((float(lon), float(lat)))
    except Exception as e:
        print(f"Sorry, invalid input ({e})")

# Transpose the coordinate pairs [(a, b), (c, d), (e, f)] into [(a, c, e), (b, d, f)]
lons, lats = zip(*coords)

# Compute averages (NB: this does not take wrapping around the globe into account at all)
avg_lon = sum(lons) / len(lons)
avg_lat = sum(lats) / len(lats)

print(avg_lon, avg_lat, sep=", ")

推荐阅读