[英]Displaying nodes sorted by distance to a given node in Python
I have a number of nodes, each has an x-axis and y-axis values which indicate a distance from each other. 我有许多节点,每个节点都有一个x轴和y轴值,表示彼此之间的距离。 For example,
例如,
nodes = [
{'name': 'node1', 'x': 2, 'y': 4, 'friend': True},
{'name': 'node2', 'x': -3, 'y': 2, 'friend': True},
{'name': 'node3', 'x': 5, 'y': 0, 'friend': False},
{'name': 'node4', 'x': -6, 'y': 1, 'friend': False},
{'name': 'node5', 'x': 0, 'y': 3, 'friend': True}
]
I need to create a function that returns only nodes who are friends sorted by a distance to a given node (say main_node = nodes[0]
) based on the X and Y values. 我需要创建一个函数,该函数仅返回根据X和Y值按给定节点的距离(例如
main_node = nodes[0]
)排序的朋友节点。
I would appreciate your help. 多谢您的协助。
The sort function takes a key parameter: sort函数采用一个关键参数:
main_node = nodes[0]
nodes.sort(key=lambda node: math.hypot(node["x"] - main_node["x"], node["y"] - main_node["y"]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.