Python字典循环中的关键问题

时间:2017-09-04 09:09:44

标签: python dictionary

我要写一个函数buildtour(start, locations),其中start是一个字符串,对应于位置中的位置名称。游览应包括距离“开始”最近的连续位置。举个例子:

print(buildtour("myhotel", [("ngv", 4, 0), ("town hall", 4, 4),("myhotel",  2, 2), ("fed square",  4, 2)]))

应该返回

["myhotel", "fed square", "ngv", "town hall"]

输入通过提交自动完成,因此位置始终在变化,因此无法手动将其定义到字典中。我可以看到在我定义的循环中开始是最近的位置(应该是巡视的下一个起始点),但它返回一个键错误。 我目前的代码是:

import math

def distance(x1, y1, x2, y2):                                                    
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)


def buildtour(start, locations):
    tour_list = [start]
    places = [u[0] for u in locations]
    coordinates = {}
    for item in locations:
      coordinates[item[0]] = item[1:]
    i = 0
    while i <= len(coordinates):
        p = 0
        distances = []
        x2y2 = coordinates.pop(start)
        x2 = x2y2[0]
        y2 = x2y2[1]
        x1 = [j[0] for i, j in coordinates.items()]
        y1 = [j[1] for i, j in coordinates.items()]
        while p <= (len(coordinates)-1):
            avg_distance = distance(x1[p], y1[p], x2, y2)
            distances.append(avg_distance)
            p += 1
            closest_place = sorted(zip(distances, places), key=lambda distances: distances[0])
            closest_place = [u[1] for u in closest_place][0]
            tour_list.append(closest_place)
        start = closest_place
    return tour_list

提前致谢!

2 个答案:

答案 0 :(得分:0)

尝试pop

问题是start是一种方法,它接受要删除的列表的索引,而不是字符串(例如,您的GraphQL runtime = GraphQL.newGraphQL(schema) .instrumentation(new MaxQueryDepthInstrumentation(MAX_DEPTH)) .build(); 的值码)。

答案 1 :(得分:0)

如果您使用词典,您的代码会变短。您可以动态创建它,名称为键,坐标为值。

如果您只使用距离对地点进行排序,则甚至不需要使用math.sqrt

start = "myhotel"

locations = [("ngv", 4, 0), ("town hall", 4, 4),
             ("myhotel",  2, 2), ("fed square",  4, 2)]
locations_dict = {n: (x, y) for n, x, y in locations}
# => {'ngv': (4, 0), 'town hall': (4, 4), 'myhotel': (2, 2), 'fed square': (4, 2)}

def distance2(name1, name2, locations_dict):
    x1, y1, x2, y2 = *locations_dict[name1], *locations_dict[name2]
    return (x2 - x1)**2 + (y2 - y1)**2

print(sorted(locations_dict.keys(),
             key=lambda name: distance2(start, name, locations_dict)))
# => ['myhotel', 'fed square', 'ngv', 'town hall']

请注意,在Python中,您几乎不必定义数组并以旧方式进行操作,首先初始化它们并逐个添加元素。这可能是更短,更Pythonic的方式。