本文介绍了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 元组(一个不可变列表),其中元素Working"位于索引 0,Retired"位于索引 1.

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(真)或 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 不总是有一个三元运算符?简单的答案是 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.

这篇关于Python 条件运算符的解决方法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:45