简体   繁体   English

如何使用Python使用backet实现if语句?

[英]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. 我看到了Python的用法,这很干净,但是我不太理解这种用法​​,也无法搜索任何有用的解释。

  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 a<0是返回true or false的条件,即1/0

(3,2) is a tuple with 3 and 2 as elements (3,2)是一个以32为元素的元组

if the condition is true statement will be indexing the element at index 1 else it will indexing to element 0 如果条件为true语句将在索引1处索引该元素,否则它将索引至元素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 条件结果为01因为在python中, True means 1False 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'. 这些文档确实并没有说太多,但是Python的Zen确实指出“简单胜于复杂”,并且“可读性很重要”。 You should use the first option. 您应该使用第一个选项。

You could also use Python's ternary operator : 您还可以使用Python的三元运算符

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

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

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