其他人也问过类似的问题,但答案对我没有帮助。我是一个初学者,正在完成一个教程,并努力完成这最后一步。你知道吗
我有一个邻居列表,并创建了一个函数(称为distance_all()
),对于给定的邻居,该函数将返回一个列表,其中包含每个其他邻居与给定邻居的距离。现在我正在尝试编写一个函数,将列表从最近的邻居排序到最远的邻居,但我无法让它工作。我还需要函数接受一个可选的第三个参数,该参数指定返回多少个邻居。你知道吗
以下是邻居的原始列表:
neighbors = [{'name': 'Fred', 'avenue': 4, 'street': 8},
{'name': 'Suzie', 'avenue': 1, 'street': 11},
{'name': 'Bob', 'avenue': 5, 'street': 8},
{'name': 'Edgar', 'avenue': 6, 'street': 13},
{'name': 'Steven', 'avenue': 3, 'street': 6},
{'name': 'Natalie', 'avenue': 5, 'street': 4}]
运行计算距离的函数时,得到以下结果:
#input
distance_all(fred, neighbors)
#output
[{'name': 'Suzie', 'avenue': 1, 'street': 11, 'distance': 4.242640687119285},
{'name': 'Bob', 'avenue': 5, 'street': 8, 'distance': 1.0},
{'name': 'Edgar', 'avenue': 6, 'street': 13, 'distance': 5.385164807134504},
{'name': 'Steven', 'avenue': 3, 'street': 6, 'distance': 2.23606797749979},
{'name': 'Natalie', 'avenue': 5, 'street': 4, 'distance': 4.123105625617661}]
现在我尝试编写一个函数,它(1)运行distance_all()
函数,(2)从最近到最远对输出列表进行排序,(3)有一个可选的第三个参数,指定要在输出列表中包含多少个邻居。我还没有走到第三步,因为我正在努力与第二步,但任何帮助是感激的。我试过很多方法,但这是我最近的一次尝试:
def nearest_neighbors(first_neighbor, neighbors, number = None):
neighbor_distance = [distance_all(first_neighbor, neighbors)]
return (sorted(neighbor_distance, key = lambda i: i['distance']))
当我运行nearest_neighbors(fred, neighbors, 2)
时,我得到错误TypeError: list indices must be integers or slices, not str
。我不知道我做错了什么。谢谢你的帮助。你知道吗
使用
list
切片例如:
演示:
输出:
您的错误是因为neighbor\u distance中的列表,neighbor\u distance=distance\u all(first\u neighbor,neighbors)而不是neighbor\u distance=[distance\u all(first\u neighbor,neighbors)]不会抛出错误。当然,仅此更改并不能解决您的总体问题,上面的答案中提到的列表切片是解决问题的最佳方法。你知道吗
相关问题 更多 >
编程相关推荐