排序方法示例代码如下:
from geopy.distance import geodesic
# 创建一个包含地理位置信息的列表
locations = [
{'name': 'A', 'latitude': 40.7128, 'longitude': -74.0060},
{'name': 'B', 'latitude': 34.0522, 'longitude': -118.2437},
{'name': 'C', 'latitude': 51.5074, 'longitude': -0.1278},
{'name': 'D', 'latitude': 35.6895, 'longitude': 139.6917}
]
# 定义一个函数,计算两个地理位置之间的距离
def calculate_distance(location1, location2):
point1 = (location1['latitude'], location1['longitude'])
point2 = (location2['latitude'], location2['longitude'])
return geodesic(point1, point2).kilometers
# 使用sorted函数按照地理距离属性对列表进行排序
sorted_locations = sorted(locations, key=lambda x: calculate_distance(x, {'latitude': 0, 'longitude': 0}))
# 输出排序结果
for location in sorted_locations:
print(location['name'])
这段代码首先引入了geopy库中的geodesic函数,用于计算两个地理位置之间的距离。然后创建一个包含地理位置信息的列表,每个位置信息包括名称、纬度和经度。接下来定义了一个calculate_distance函数,用于计算两个地理位置之间的距离。最后使用sorted函数按照地理距离属性对列表进行排序,并输出排序结果。
上一篇:按嵌套表计数进行排序
下一篇:按嵌套对象日期排序