问题描述
从我读过,我发现一个内置的三元运算符不存在(我会很乐意多了解一下。)
From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
我发现下面的code作为替代:
I found the following code as a substitute:
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
我不明白这是如何code工作;任何人都可以解释我是如何实际上是code为工作?我也有兴趣知道为什么三元运算符不存在;这个任何参考或链接将矿石有用。
I couldn't understand how this code works; can anyone explain me how actually the code is working? I am also interested to know why the ternary operator doesn't exist; any references or links about this will be ore useful.
我在Windows Vista上运行的Python 2.6.4。
I'm running Python 2.6.4 on Windows Vista.
推荐答案
Python有一个结构,它是有点像在C三元运算等。它的工作原理是这样的:
Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:
my_var = "Retired" if age > 65 else "Working"
和相当于这个C code:
and is equivalent to this C code:
my_var = age > 65 ? "Retired" : "Working";
至于如何code您发布的作品,让我们通过它一步:
As for how the code you posted works, let's step through it:
("Working","Retired")
创建了一个2元组(不可变列表)与索引0元素工作和退役索引1。
creates a 2-tuple (an immutable list) with the element "Working" at index 0, and "Retired" at index 1.
var>65
如果无功大于65,假如果不返回True。当应用于一个指数,它被转换成1(真)或0(假)。因此,该布尔值提供一个索引在同一行中创建的元组
returns True if var is greater than 65, False if not. When applied to an index, it is converted into 1 (True) or 0 (False). Thus, this boolean value provides an index into the tuple created on the same line.
为什么没有Python中一直有一个三元运算符?简单的答案是,吉多·范罗苏姆,巨蟒的作者,不喜欢/不想要它,显然认为这是谁的看到大量嵌套不必要的结构,可能会导致混乱code(以及任何三元运营商在C能大概一致)。但对于Python 2.5,他心软了,并添加上面看到的语法。
Why hasn't Python always had a ternary operator? The simple answer is that Guido van Rossum, the author of Python, didn't like/didn't want it, apparently believing that it was an unnecessary construct that could lead to confusing code (and anyone who's seen massively-nested ternary operators in C can probably agree). But for Python 2.5, he relented and added the grammar seen above.
这篇关于如何Python的条件运算解决方法的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!