Python 创建节点从外部到中心的栅格/网格
python新手,如果这不清楚,我很抱歉,但我正在尝试构造一个x轴范围为-4000到4000,y轴范围为-4000到4000的网格 我试图将每个轴拆分为100个节点,但我希望节点1位于(-4000,-4000)即左下角,基本上是为了使节点绕过进入的网格的外部,因此我的最终节点将位于网格的正中心 我试着这样做,因为我正在运行for循环,在读取节点的x和y值时,我需要以正确的顺序循环节点。我以前从未在python上制作过网格,因此非常感谢您的帮助Python 创建节点从外部到中心的栅格/网格,python,grid,mesh,Python,Grid,Mesh,python新手,如果这不清楚,我很抱歉,但我正在尝试构造一个x轴范围为-4000到4000,y轴范围为-4000到4000的网格 我试图将每个轴拆分为100个节点,但我希望节点1位于(-4000,-4000)即左下角,基本上是为了使节点绕过进入的网格的外部,因此我的最终节点将位于网格的正中心 我试着这样做,因为我正在运行for循环,在读取节点的x和y值时,我需要以正确的顺序循环节点。我以前从未在python上制作过网格,因此非常感谢您的帮助 谢谢如果您更关心可读性而不是性能,我建议您首先创建方
谢谢如果您更关心可读性而不是性能,我建议您首先创建方形网格,然后以“螺旋”配置对其进行排序 考虑到您的节点类:
class Node:
"Node of the grid"
def __init__(self, x, y):
self.x = x
self.y = y
您希望为每个轴创建100个节点(第一个在-4000,一个在0,最后一个在3200):
然后,为了让它按你想要的方式排序,你需要类似于极坐标的东西,然后按半径再按角度排序(我说的类似是因为你的节点被排列成一个正方形而不是一个圆形)。此处的半径应为max(abs(x)、abs(y)
,而不是正常半径
排序代码如下所示:
import math
sorted_nodes = []
for node in nodes:
# We take atan2 to compute the phase but the starting point would not be on bootom left corner
# So we need to add a constant (0.001 is a small number to make the bottom left corner to have maximum value)
# We use this trick to still be able in reverse order
phase = (math.atan2(node.y, node.x) + 3 * math.pi / 4 - 0.001) % (2 * math.pi)
sorted_nodes.append((max(abs(node.x),abs(node.y)), phase, node))
sorted_nodes = sorted(sorted_nodes, reverse=True) # Sort first by radius, then by the phase
sorted_nodes
列表是一个元组,第三个参数是排序良好的节点(您可以得到一个节点列表,其中[t[2]表示排序后的_nodes中的t]
)
注意:列表是顺时针的
import math
sorted_nodes = []
for node in nodes:
# We take atan2 to compute the phase but the starting point would not be on bootom left corner
# So we need to add a constant (0.001 is a small number to make the bottom left corner to have maximum value)
# We use this trick to still be able in reverse order
phase = (math.atan2(node.y, node.x) + 3 * math.pi / 4 - 0.001) % (2 * math.pi)
sorted_nodes.append((max(abs(node.x),abs(node.y)), phase, node))
sorted_nodes = sorted(sorted_nodes, reverse=True) # Sort first by radius, then by the phase