如何简化这个非常长的if语句?

时间:2010-11-03 14:35:48

标签: python graphics if-statement modulus simplification

如何简化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):
            ...

6 个答案:

答案 0 :(得分:15)

这是相同的:

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

答案 1 :(得分:12)

基本上你正在平铺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]:
           ...

这是一种非常简单和通用的方法,可以轻松修改模式。

答案 2 :(得分:7)

有两个简单的修复:

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

此外,<= 4(或< 5)的测试实际上是多余的,因为 lxly的每个值都将是&lt; 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):

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

cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if (x % 5, y % 5) in cross_fields:

答案 3 :(得分:2)

根据Konrad的回答,您可以进一步简化:

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 (1 < lx < 5 and 1 < y < 5 and 
           (lx, ly) not in ((2, 2), (4, 2), (2, 4), (4, 2))):

答案 4 :(得分:1)

康拉德的第二个答案: -

cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]

for y in range(MAP_HEIGHT):
  for x in range(MAP_WIDTH):
    if (x % 5, y % 5) in cross_fields:

可能是最好的。

但是,我会做出贡献: -

for y in range(MAP_HEIGHT):
  for x in range(MAP_WIDTH):
    lx = x % 5
    ly = y % 5
    if (lx > 1 and ly == 3) or (ly > 1 and lx == 3):

答案 5 :(得分:0)

优化像这样的逻辑函数的一般解决方案是Karnaugh map。您的真值表将是您想要的字面加上形状,行和列是模块化测试。