簡體   English   中英

在Python中顯示按與給定節點的距離排序的節點

[英]Displaying nodes sorted by distance to a given node in Python

我有許多節點,每個節點都有一個x軸和y軸值,表示彼此之間的距離。 例如,

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} 
]

我需要創建一個函數,該函數僅返回根據X和Y值按給定節點的距離(例如main_node = nodes[0] )排序的朋友節點。

多謝您的協助。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM