문제

There are two variables, a and b, and each can either be positive or negative. 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

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

This works because, in Python boolean values are actually integers. The following are true in 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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top