【发布时间】:2010-12-01 14:41:18
【问题描述】:
我在 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 语句,有没有更好的方法来做到这一点?有效率的东西会很好,因为这部分逻辑被调用了几百万次......它用于模拟退火。
提前致谢。另外,标题的措辞有什么更好的方式?
【问题讨论】:
-
您的格式丢失,请编辑并重新发布。
-
@whatnick,好点了吗?
-
格式没问题——但你的意思是左列和右列,而不是左行和右行。
-
您的“左上角”是 x == 0 和 y == 0 ...在大多数人的惯例中,这将是“左下角”。甚至 Antipodeans 也不会这样做 :-)
-
@John Machin:屏幕左上角像素的坐标是
x=0, y=0。左下角是x=0, y=screen_height。
标签: python arrays list performance