简体   繁体   English

在Python中显示按与给定节点的距离排序的节点

[英]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.

相关问题 有向图中的深度:在距离给定节点 k 处查找节点 - Depth in Directed Graph: Finding nodes at k distance from a given node 如何在给定孤立节点与其非相邻节点之间的边缘距离的情况下预测列车系统的图网络? - How to predict graph network given edge distance between isolated nodes and their non-adjacent node for a train system? 我需要找到源节点和目标节点之间的最短路径(距离)。 鉴于必须包含某些节点 - I need to find the shortest path (distance) between a source node and a target node. Given that certain nodes MUST be included 在 networkx 和 python 中查找距离内的节点 - Find nodes within distance in networkx and python 仅检查图中两个节点是否在给定距离(路径长度)内 - Check only if two nodes are within a given distance (path length) in a Graph 节点的平均距离按节点数 python 的对数增加 - The mean distance of the nodes increases by log of the number of nodes python Python:如何创建具有给定分布的距离网络? - Python: how to create a distance network with a given distribution? 给出python中的距离计算网格值 - Calculating grid values given the distance in python Python:如何将给定距离内的点组合在一起? - Python: how to group together points in a given distance? 给定距离矩阵的 Python 中的最近邻 - Nearest Neighbors in Python given the distance matrix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM