操作字典列表中的数据(Google API 距离矩阵)

Manipulating data from a list of dictionaries (Google API Distance Matrix)

我需要帮助。我正在使用 Google API 距离矩阵和 Python 3.5 从另一个点找出最近的点。我有下面的字典列表,我想要一个像这样的输出:

"Origin 1: the closest destination is Destination 1 (1504 m)"

"Origin 2: the closest destination is Destination 1 (2703 m)"

等等..

知道如何获得此输出吗?

response=[{'rows': [{'elements': [{'distance': {'text': '1.5 km', 'value': 1504},\
'duration': {'text': '4 mins', 'value': 247}, 'status': 'OK'}]}],\
'origin_addresses': ['Origin 1'], 'destination_addresses': ['Destination 1'], 'status': 'OK'},\
{'rows': [{'elements': [{'distance': {'text': '2.7 km', 'value': 2703},\
'duration': {'text': '7 mins', 'value': 430}, 'status': 'OK'}]}],\
'origin_addresses': ['Origin 2'], 'destination_addresses': ['Destination 1'], 'status': 'OK'},\
{'rows': [{'elements': [{'distance': {'text': '4.8 km', 'value': 4753},\
'duration': {'text': '10 mins', 'value': 586}, 'status': 'OK'}]}],\
'origin_addresses': ['Origin 1'], 'destination_addresses': ['Destination  2'], 'status': 'OK'},\
{'rows': [{'elements': [{'distance': {'text': '6.0 km', 'value': 5952},\
'duration': {'text': '13 mins', 'value': 769}, 'status': 'OK'}]}],\
'origin_addresses': ['Origin 2'], 'destination_addresses': ['Destination 2'], 'status': 'OK'}]\

下面的代码将找到距每个原点的最短距离,然后按照示例格式显示结果:

from collections import OrderedDict

def find_closest(distances):
    closest = OrderedDict()
    for distance in distances:
        origin = distance['origin_addresses'][0]
        destination = distance['destination_addresses'][0]
        value = distance['rows'][0]['elements'][0]['distance']['value']

        if origin not in closest or value < closest[origin][1]:
            closest[origin] = (destination, value)

    return closest

def format_closest(closest):
    for origin, (destination, value) in closest.items():
        yield "%s: the closest destination is %s (%d m)" % (origin, destination, value)

for line in format_closest(find_closest(response)):
    print(line)

请注意,我使用了 OrderedDict 以保留在您的回复中找到的顺序。如果这对您来说无关紧要,您可以将 OrderedDict() 替换为 {} .

要获得格式化结果列表,只需使用:

list(format_closest(find_closest(response)))