Python“如果 X == Y 和 Z”语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3629586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:00:09  来源:igfitidea点击:

Python "if X == Y and Z" syntax

pythonif-statement

提问by bsamek

Does this:

做这个:

if key == "name" and item:

mean the same as this:

意思和这个一样:

if key == "name" and if key == "item":

If so, I'm totally confused about example 5.14 in Dive Into Python. How can key be equal to both "name" and item? On the other hand, does "and item" simply ask whether or not item exists as a variable?

如果是这样,我对Dive Into Python 中的示例 5.14完全感到困惑。键怎么可以同时等于“名称”和项目?另一方面,“和项目”是否只是询问项目是否作为变量存在?

采纳答案by Manoj Govindan

if key == "name" and item:means if (key == "name") and (item evaluates to True).

if key == "name" and item:是指if (key == "name") and (item evaluates to True)

Keep in mind that (item evaluates to True)is possible in several ways. For example if (key == "name") and []will evaluate to False.

请记住,这(item evaluates to True)可以通过多种方式实现。例如if (key == "name") and []将评估为False.

回答by froadie

No, you have to repeat the expression. It evaluates as 2 separate conditions, and checks if both are true -

不,你必须重复这个表达式。它评估为 2 个单独的条件,并检查两者是否都为真 -

  1. x == y
  2. z
  1. x == y
  2. z

Check the Python documentationfor a list of what is considered False in Python

检查Python 文档以获取Python中被视为 False 的列表

(However, interesting to note that, as opposed to other languages, the following:

(然而,有趣的是,与其他语言相比,以下内容:

if 3 < x < 6

is equivalent to

相当于

if x > 3 and x < 6

)

)

回答by Victor Neo

If you look at the code for example 5.14:

如果您查看示例 5.14 的代码:

def __setitem__(self, key, item):         
    if key == "name" and item:            
        self.__parse(item)                
    FileInfo.__setitem__(self, key, item)

itemis a variable, similar to how key is.

item是一个变量,类似于 key 是多少。

It can be used in the ifstatement if it evaluates into either trueor false.

if如果它的计算结果为true或,则可以在语句中使用它false

eg.

例如。

happy = True
name = "Peter"
if name == "Peter" and happy:
    print name + " is happy!"

回答by brandizzi

Manoj explained it well. Here goes some complementary notes.

Manoj 解释得很好。这里有一些补充说明。

The pseudocode

伪代码

if key == "name" or if key == "item":

should be this way:

应该是这样的:

if key == "name" or key == "item":

An interesting idiom to do it is:

一个有趣的成语是:

if key in ("name", "item"):

but it is more useful for really large conditions where you just want to know if some value is equal to any other value from a list.

但它对于非常大的条件更有用,在这种情况下,您只想知道某个值是否等于列表中的任何其他值。

回答by kindall

Others have explained how the expression you're asking about is evaluated. An important thing to know is that if the first operand of the "and" operator evaluates to false, the second one is never evaluated, because the result of "and" is always false if one operand is false, and if you know the first operand is false, then the whole "and" is false and you don't have to evaluate the second. This is called "short-circuiting" and applies to "or" as well as "and" (except that "or" is always true when either operand is true, so the second operand is evaluated only when the first is false).

其他人已经解释了如何评估您所询问的表达式。要知道的重要一点是,如果“and”运算符的第一个操作数的计算结果为 false,则永远不会计算第二个操作数,因为如果一个操作数为 false,并且如果您知道第一个操作数,则“and”的结果始终为 false操作数为假,那么整个“和”为假,您不必评估第二个。这称为“短路”,适用于“或”和“与”(除了当任一操作数为真时“或”始终为真,因此仅当第一个操作数为假时才计算第二个操作数)。

The other thing you need to know is that the result of the whole "and" operation is the value of the last operand evaluated. Since things other than the literal constants True and False are considered logically true or false, this fact (combined with short-circuiting) can be used as a substitute for "if" statements in some situations, and you will occasionally see it used that way.

您需要知道的另一件事是整个“与”操作的结果是最后一个操作数的值。由于字面常量 True 和 False 以外的东西在逻辑上被认为是真或假,这个事实(与短路相结合)可以在某些情况下用作“if”语句的替代品,您偶尔会看到它以这种方式使用.

For example, "x or y" evaluates to x if x is true, but to y if x is false. Sometimes this is used to provide defaults for missing values:

例如,如果 x 为真,“x 或 y”的计算结果为 x,但如果 x 为假,则计算为 y。有时这用于为缺失值提供默认值:

name = raw_input("Enter your name: ") or "dude"
print "Hello, %s!" % name

If you don't enter anything at the prompt, just hit Enter, the return value of raw_input is the empty string, "", which is considered false. Since the left branch of the "or" is false, it doesn't short-circuit, and the right branch is evaluated, so the result of the "or" is "dude." If you do enter a value at the prompt, the right branch never gets evaluated, due to short-circuiting, and so the value of the "or" is whatever you entered.

如果在提示符下什么都不输入,直接回车,raw_input的返回值是空字符串"",被认为是false。由于“or”的左分支为false,不会短路,对右分支求值,所以“or”的结果为“dude”。如果您确实在提示符下输入了一个值,由于短路,正确的分支永远不会被评估,因此“或”的值就是您输入的任何值。

A lot of people consider abusing Boolean operators this way to be poor style now that Python has "x if y else z," but this particular use strikes me as readable enough. (But this is about the only one!) "The value is this, or that if it's empty." Compare it to the following:

很多人认为以这种方式滥用布尔运算符是一种糟糕的风格,因为 Python 有“x if y else z”,但这种特殊的用法让我觉得可读性很强。(但这是唯一的一个!)“值是这个,或者如果它是空的。” 将其与以下内容进行比较:

name = raw_input("Enter your name: ")
name = name if name else "dude"
print "Hello, %s!" % name

回答by Dave Aaron Smith

If, hypothetically, you did want

如果,假设,你确实想要

if key == "name" and if key == item:

you could do this

你可以这样做

if key == "name" == item:

回答by Tony Veijalainen

@Victor Neo: Also you do not need separate boolean:

@Victor Neo:你也不需要单独的布尔值:

for happy in (False, "Peter", '', "Susan" , []):
    print(happy + ' is happy.' if happy else 'Everybody is bored.')

If statement is preferred over using orand andwith non-booleans, which emulated the effect before value if condition else valuebecame available in Python.

If 语句优于 usingorandwith non-booleans,后者value if condition else value在 Python 中可用之前模拟了效果。