有效的网格(数组)定位方法
我在用Python表示一个网格,使用的是一个二维列表。我想在这个列表中选一个点(x,y),然后确定它的位置,比如它是在右边、左上角,还是在中间的某个地方……
目前我检查位置的方式是这样的:
# left column, not a corner
if x == 0 and y != 0 and y != self.dim_y - 1:
pass
# right column, not a corner
elif x == self.dim_x - 1 and y != 0 and y != self.dim_y - 1:
pass
# top row, not a corner
elif y == 0 and x != 0 and x != self.dim_x - 1:
pass
# bottom row, not a corner
elif y == self.dim_y - 1 and x != 0 and x != self.dim_x - 1:
pass
# top left corner
elif x == 0 and y == 0:
pass
# top right corner
elif x == self.dim_x - 1 and y == 0:
pass
# bottom left corner
elif x == 0 and y == self.dim_y - 1:
pass
# bottom right corner
elif x == self.dim_x - 1 and y == self.dim_y - 1:
pass
# somewhere in middle; not an edge
else:
pass
在确定位置后,我会让某个函数执行一些操作。
dim_x和dim_y是列表的尺寸。
有没有更好的方法来做这个,而不需要那么多的if-else判断?如果能更高效就更好了,因为这个逻辑会被调用几百万次……这是为了模拟退火算法。
提前谢谢你们。另外,标题有没有更好的表达方式?
6 个回答
如果我理解得没错,你有一组坐标(x,y),它们在一个网格里。你想知道,给定任何一个坐标,它是处于网格内部还是在边缘上。
我会先把这个网格进行标准化,也就是把它的起点设为(0,0),右上角设为(1,1)。这样一来,我只需要知道坐标的值,就能判断它的位置。让我来解释一下。
0) 让 _max 代表最大值,_min 代表最小值,比如说 x_min 就是坐标 x 的最小值;让 _new 代表标准化后的值。
1) Given (x,y), compute: x_new = (x_max-x)/(x_max-x_min) and y_new=(y_max-y)/(y_max-y_min).
2) [this is pseudo code]
switch y_new:
case y_new==0: pos_y='bottom'
case y_new==1: pos_y='top'
otherwise: pos_y='%2.2f \% on y', 100*y_new
switch x_new:
case x_new==0: pos_x='left'
case x_new==1: pos_x='right'
otherwise: pos_x='%2.2f \% on x', 100*x_new
print pos_y, pos_x
It would print stuff like "bottom left" or "top right" or "32.58% on y 15.43% on x"
Hope that helps.
# initially:
method_list = [
bottom_left, bottom, bottom_right,
left, middle, right,
top_left, top, top_right,
]
# each time:
keyx = 0 if not x else (2 if x == self.dim_x - 1 else 1)
keyy = 0 if not y else (2 if y == self.dim_y - 1 else 1)
key = keyy * 3 + keyx
method_list[key](self, x, y, other_args)
这个还没经过测试……不过大致的思路应该能看得出来。
更新:在“因为这部分逻辑会被调用几百万次,所以希望能有点效率”之后,目标发生了很大变化:
最开始你不喜欢那一连串的测试,觉得每个8种情况都要调用一个函数。如果你想在Python中提高速度:保留那一连串的测试,然后把每种情况的处理放在一起,而不是去调用一个函数。
你能用psyco吗?另外,考虑一下使用Cython。
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会继续进行。
比如说,你可能希望在用户输入一个数字时,程序才开始计算。如果用户没有输入数字,程序就会停下来,等着用户输入。这种情况就需要用到“条件语句”。
条件语句就像是一个检查点,程序会在这里判断某个条件是否成立。如果成立,程序就会执行某些代码;如果不成立,程序可能会执行其他代码,或者什么都不做。
总之,条件语句帮助我们控制程序的执行流程,让程序更智能,能够根据不同的情况做出不同的反应。
def location(x,y,dim_x,dim_y):
index = 1*(y==0) + 2*(y==dim_y-1) + 3*(x==0) + 6*(x==dim_x-1)
return ["interior","top","bottom","left","top-left",
"bottom-left","right","top-right","bottom-right"][index]