Issue
I saw some variations of the following simple piece of code:
if dist_1>dist_2 :
print enemy_2
else:
print enemy_1
Variation 1:
print (enemy_1, enemy_2)[dist_1 > dist_2]
Variation 2:
e1, d1, e2 = (raw_input() for _ in '123')
print (e1, e2)[d1 > raw_input()]
Can someone please explain how this print (x,y)[x>y]
code works?
Solution
Booleans are actually a subclass of integers in Python:
isinstance(True, int)
isinstance(False, int)
are both true statements. So you can index a two-element sequence with a boolean. If the boolean is False
, you will get the first element. If the boolean is True
, you will get the second element.
The expression (enemy_1, enemy_2)
creates a two-element tuple
. [dist_1 > dist_2]
provides the boolean index. The print
is incidental; it is just used to output the result.
Answered By - Mad Physicist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.