如何简化这个很长的ifstatement?

2024-09-30 22:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何简化这个if语句?它是一个加号: http://i.stack.imgur.com/PtHO1.png

如果语句完成,则在x和y坐标处设置一个块。在

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
            (y%5 == 2 or y%5 == 3 or y%5 == 4) and \
            not(x%5 == 2 and y%5 == 2) and \
            not(x%5 == 4 and y%5 == 2) and \
            not(x%5 == 2 and y%5 == 4) and \
            not(x%5 == 4 and y%5 == 4):
            ...

Tags: orandincomhttpmapforif
3条回答

有两个小问题:

  • 缓存x % 5y % 5的结果
  • 使用in或链式<来测试这些值:

另外,<= 4(或< 5)的测试实际上是多余的,因为lxly的每个值都是<;5。在

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        lx = x % 5 # for local-x
        ly = y % 5 # for local-y
        if lx > 1 and y > 1 and \
           not (lx == 2 and ly == 2) and \
           not (lx == 4 and ly == 2) and \
           not (lx == 2 and ly == 4) and \
           not (lx == 4 and ly == 4):

或者您可以保留一个实际允许的元组列表:

^{pr2}$

基本上你是平铺一个5x5二进制模式。这里有一个明确的表述:

pattern = [[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 1, 0],
           [0, 0, 1, 1, 1],
           [0, 0, 0, 1, 0]]

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if pattern[x%5][y%5]:
           ...

这是一个非常简单和通用的方法,它可以很容易地修改模式。在

这是一样的:

if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): 

相关问题 更多 >