Python 条件运算符解决方法如何工作?
问题描述
根据我的阅读,我发现内置的三元运算符不存在(我很乐意了解更多信息.).
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.).
我找到了以下代码作为替代:
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
我无法理解这段代码是如何工作的;谁能解释一下代码实际上是如何工作的?我也很想知道为什么三元运算符不存在;任何有关此的参考或链接都会很有用.
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 代码:
and is equivalent to this C code:
my_var = age > 65 ? "Retired" : "Working";
至于您发布的代码是如何工作的,让我们逐步介绍一下:
As for how the code you posted works, let's step through it:
("Working","Retired")
创建一个 2 元组(一个不可变列表),索引 0 为元素Working",索引 1 为Retired".
creates a 2-tuple (an immutable list) with the element "Working" at index 0, and "Retired" at index 1.
var>65
如果 var 大于 65,则返回 True,否则返回 False.应用于索引时,它会转换为 1 (True) 或 0 (False).因此,这个布尔值提供了在同一行创建的元组的索引.
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 不是一直都有三元运算符?简单的答案是 Python 的作者 Guido van Rossum 不喜欢/不想要它,显然认为它是一种不必要的构造,可能导致混淆代码(以及任何在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.
相关文章