简体   繁体   English

如何在Python中缩短if if和elif代码

[英]How to shorten this if and elif code in Python

There are two variables, a and b , and each can either be positive or negative. 有两个变量, ab ,每个变量可以是正数或负数。 An identifier needs to be set based on the four conditions. 需要根据四个条件设置标识符。 How could I minimize the code given below so that the same task could be achieved? 我怎样才能最小化下面给出的代码,以便可以实现相同的任务? A list comprehension or bitwise operation or something along those lines might shorten this, but I have no idea how to do this. 列表理解或按位操作或类似的操作可能会缩短这一点,但我不知道如何做到这一点。

if a > 0 and b > 0:
    direction = 'NORTH EAST'

elif a > 0 and b < 0:
    direction = 'SOUTH EAST'

elif a < 0 and b < 0:
    direction = 'SOUTH WEST'

elif a < 0 and b > 0:
    direction = 'NORTH WEST'

You can use conditional expressions like this 您可以使用这样的条件表达式

("NORTH " if b > 0 else "SOUTH ") + ("EAST" if a > 0 else "WEST")

There is one more hack which can be used here 还有一个可以在这里使用的hack

["SOUTH ", "NORTH "][b > 0] + ["WEST", "EAST"][a > 0]

This works because, in Python boolean values are actually integers . 这是有效的,因为在Python中, 布尔值实际上是整数 The following are true in Python Python中有以下内容

print 1 == True
# True
print 0 == False
# True

Use conditional expressions: 使用条件表达式:

direction = ' '.join(['NORTH' if a > 0 else 'SOUTH',
                      'EAST' if b > 0 else 'WEST'])

Demo: 演示:

>>> for a in (-1, 1):
...     for b in (-1, 1):
...         print ' '.join(['NORTH' if a > 0 else 'SOUTH',
...                         'EAST' if b > 0 else 'WEST'])
... 
SOUTH WEST
SOUTH EAST
NORTH WEST
NORTH EAST

Your's looks fine. 你看起来很好。 Here is the same thing using a conditional expression: 使用条件表达式是一回事:

>>> 
>>> a = 1
>>> b = -1
>>> lat = 'NORTH' if a > 0 else 'SOUTH'
>>> lon = 'EAST' if b > 0 else 'WEST'
>>> direction = '{} {}'.format(lat, lon)
>>> direction
'NORTH WEST'
>>>

Or use a dictionary as a map 或者使用字典作为地图

map[-1] = {-1:'SOUTH WEST', 1: 'NORTH WEST'}
map[1] = {-1:'SOUTH EST', 1: 'NORTH EST'}
direction = map[a/abs(a)][b/abs(b)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM