从外到中心创建网格/节点

0 投票
1 回答
908 浏览
提问于 2025-04-18 13:31

我刚接触Python,所以如果我说得不清楚请多包涵。我想构建一个网格,x轴的范围是从-4000到4000,y轴的范围也是从-4000到4000。

我想把每个轴分成100个节点,但我希望第一个节点位于(-4000,-4000),也就是左下角。然后这些节点要沿着网格的外边缘向内移动,最终的节点会在网格的正中心。

我这样做是因为我在运行一个循环,需要按照正确的顺序遍历这些节点的x和y值。我之前没有在Python中做过网格,所以任何帮助都非常感谢。

谢谢!

1 个回答

0

如果你更关注代码的可读性而不是性能,我建议你先创建一个方形的网格,然后再把它按“螺旋”的方式排序。

考虑一下你的节点类:

class Node:
    "Node of the grid"
    def __init__(self, x, y):
        self.x = x
        self.y = y

你想在每个轴上创建100个节点(第一个节点在-4000,第二个在0,最后一个在3200):

nodes = []
for x in range(-4000, 4001, 800): # From -4000 to 4000 (included) by 800 increment  
    for y in range(-4000, 4000, 800):
        nodes.append(Node(x,y))

然后为了让它按照你想要的方式排序,你需要类似极坐标的方式,先按半径排序,再按角度排序(我说类似是因为你的节点是方形排列的,而不是圆形)。这里的半径应该是 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] for t in sorted_nodes] 来获取你的节点列表)。

注意:这个列表是顺时针方向的

撰写回答