简体   繁体   中英

How does this:Use backet to achieve if statement in Python?

I saw this usage of Python, which is very clean, but I don't really understand this usage, and can't search any useful explanation about it either.

  1. This is the normal method:

     if a < 0: b = 2 * a else: b = 3 * a 
  2. And this realizes the same purpose:

     b = a * (3,2) [a<0] 

Can someone tell me Where does the official documentation say something about the above ?

b = a * (3,2) [a<0]

a<0 is a condition returning true or false ie 1/0

(3,2) is a tuple with 3 and 2 as elements

if the condition is true statement will be indexing the element at index 1 else it will indexing to element 0

like

In [33]: (3,2)[0]
Out[33]: 3

In [34]: (3,2)[1]
Out[34]: 2

The condition results in 0 or 1 because In python True means 1 and False means 0

In [35]: True == 1
Out[35]: True

In [36]: False == 0
Out[36]: True

Use the second option for golfing purposes only. The docs really don't say much about this syntax, but The Zen of Python does state that 'Simple is better than complex', and that 'Readability counts'. You should use the first option.

You could also use Python's ternary operator :

b = a*(2 if a < 0 else 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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