简体   繁体   English

还是Python的打印语句中的关键字?

[英]Or keyword inside a print statement in Python?

How does Python decide the output of this ? Python如何确定此输出?

print([1, 2] or ["hello"])

I mean why will always print([2] or ["az"]) output [2] and not ["az"] ? 我的意思是为什么总是打印([2]或[“ az”])输出[2]而不是[“ az”]?

由于这些列表包含元素,因此它们将求值为True因此Python会打印以True字面量为先的那一个。

There are two things you have to understand here. 您必须在这里了解两件事。 First: 第一:

x or y

If x is truthy, it has the value of x (without even evaluating y , so 23 or launch_nukes() doesn't launch the nukes). 如果x为真,则其值为x (甚至不评估y ,因此23 or launch_nukes()不会启动23 or launch_nukes() )。

Otherwise, it has the value of y . 否则,其值为y

Or, as the docs put it: 或者,如文档所述

The expression x or y first evaluates x ; 表达式x or y首先计算x ; if x is true, its value is returned; 如果x为true,则返回其值; otherwise, y is evaluated and the resulting value is returned. 否则,将评估y并返回结果值。

Notice that it uses the word "true" here, not the value True . 注意,它在这里使用单词“ true”,而不是值True This is a bit confusing (even more so if you're talking out loud, or typing in ASCII without formatting…), which is why everyone says "truthy". 这有点令人困惑(如果您大声说出来或以ASCII格式输入而没有格式化……则更是如此),这就是每个人都说“真实”的原因。


So, what do "truthy" and "falsey" mean? 那么,“真实”和“虚假”是什么意思? 1 1

  • "x is truthy" does not mean x == True , it means bool(x) == True . “x是truthy” 并不意味着x == True ,这意味着bool(x) == True
  • "x is falsey" does not mean x == False , it means bool(x) == False . “x是falsey” 并不意味着x == False ,这意味着bool(x) == False

For all builtin and stdlib types: 对于所有内置和stdlib类型:

  • False is falsey. False是假。
  • None is falsey. None是假的。
  • Numeric zero values are falsey. 数字零值是错误的。
  • Empty containers are falsey. 空容器是假的。
  • Everything else is truthy. 其他一切都是真实的。

Notice that None and empty containers are falsey, but they're not equal to False . 请注意, None和空容器是false,但它们不等于False

By convention, third-party types (including types that you define 2 ) should follow the same rules. 按照约定,第三方类型(包括您定义2的类型)应遵循相同的规则。 But sometimes there are good reasons not to. 但有时有充分的理由不这样做。 (For example, a NumPy array is neither truthy nor falsey. 3 ) (例如,一个NumPy数组既不是真实的也不是虚假的。3

This is covered loosely in the same docs section : 同一文档部分中对此进行了宽松介绍

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). 在布尔运算的上下文中,以及当控制流语句使用表达式时,以下值将解释为false:False,None,所有类型的数字零以及空字符串和容器(包括字符串,元组,列表,字典) ,集合和Frozensets)。 All other values are interpreted as true. 所有其他值均解释为true。 User-defined objects can customize their truth value by providing a __bool__() method. 用户定义的对象可以通过提供__bool__()方法来自定义其真值。

The exact details for all builtin types are buried in the standard type hierarchy , which is where you learn things like whether bytes is covered by "strings and containers" (yes) or whether there's anything special about NotImplemented (nope, it's truthy). 所有内置类型的确切详细信息都埋在标准类型层次结构中 ,在这里您可以学习诸如bytes是否被“字符串和容器”覆盖(是)或NotImplemented是否有特殊之处(不,这是事实)。


So, let's go through your examples: 因此,让我们看一下您的示例:

[1, 2] or ["hello"]

Since [1, 2] is a non-empty container, it's truthy. 由于[1, 2]是一个非空容器,因此是正确的。 So this equals [1, 2] . 因此,这等于[1, 2]

[] or ["hello"]

Since [] is an empty container, it's falsey. 由于[]是一个空容器,因此是错误的。 So this equals ["hello"] . 因此,这等于["hello"]

[] == False

[] may be falsey, but it's not False , or even equal to False . []可能是错误的,但不是False ,甚至不等于False Only numbers equal other numbers, and False is the number 0 in the numeric type bool , 4 but [] is not a number. 只有数字等于其他数字和False是在数字型数字0 bool ,4,[]不是数字。 So this is False . 所以这是False


Just be glad you didn't ask about is . 只是很高兴你没有询问is :) :)


1. Technically, these terms aren't defined, even though everyone, even the core devs, uses them all the time. 1.从技术上讲,即使每个人(甚至核心开发人员)始终使用它们,也未定义这些术语。 The official reference defines things in terms of evaluating to true or false as a boolean, and then explains what that means elsewhere. 官方参考文献根据布尔值对true或false进行评估来定义事物,然后在其他地方解释含义。

2. You can control whether your types' values are truthy by defining a __bool__ method—or by defining __len__ . 2.您可以通过定义__bool__方法或定义__len__来控制类型的值是否真实。 The only things you're allowed to do are return True , return False , or raise an exception; 您唯一可以做的就是返回True ,返回False或引发异常。 if you try to return anything different, it raises a TypeError . 如果尝试返回任何不同的内容,则会引发TypeError So, everything is either truthy, or falsey, or untestable. 因此,一切都是真实的,错误的或不可测的。

3. If you try to check its truthiness, it will raise an exception. 3.如果您尝试检查其真实性,它将引发异常。 That's because NumPy uses boolean arrays widely—eg, array([1, 2]) < array([2, 1]) is array([True, False]) , and you don't want people writing if array([1, 2]) < array([2, 1]): , since whatever they're expecting it to do probably doesn't make sense. 这是因为NumPy广泛使用布尔数组-例如, array([1, 2]) < array([2, 1])array([True, False]) ,并且您不希望人们在写if array([1, 2]) < array([2, 1]): :,因为无论他们期望它做什么,都可能没有任何意义。

4. Yes, bool is a numeric type—in fact, a subclass of int . 4.是的, bool是数字类型,实际上是int的子类。 This is a little weird when you're first learning, but it turns out to be useful more often than it's dangerous, so it's not just preserved for historic reasons. 当您初次学习时,这有点奇怪,但事实证明,它比危险更有用,因此,它不仅仅是出于历史原因而被保留。

x or y [or z or z1 or z2 or ...] returns the first Truthy element in sequence, or the last Falsey element if all are Falsey. x or y [or z or z1 or z2 or ...]依次返回第一个Truthy元素,如果所有均为Falsey,则返回最后一个Falsey元素。

x and y [and z and z1 and z2 and ...] returns the first Falsey element in sequence, or the last Truthy element if all are Truthy. x and y [and z and z1 and z2 and ...]依次返回第一个Falsey元素,如果所有元素均为Truthy,则返回最后的Truthy元素。


Python has a notion of Truthiness and Falsiness that is separate from True and False . Python的TrueFalse概念与TrueFalse分开。 An empty list is not False , but it is Falsey . 空列表不是False ,而是Falsey bool(something_truthy) == True and bool(something_falsey) == False . bool(something_truthy) == Truebool(something_falsey) == False

Most things are Truthy, so it's easier to list the Falsey things: 大多数事情都是真实的,因此列出Falsey事情会更容易:

  • 0 (note that -1 is Truthy) 0 (请注意-1是真实的)
  • None
  • Empty collections ( [] , {} , set() , "" , and etc. Note that non-empty collections containing entirely Falsey elements are still truthy eg [None, None, None, None] ) 空集合( []{}set()""等)。请注意,包含完全Falsey元素的非空集合仍然是真实的,例如[None, None, None, None]
  • False

Everything else is Truthy. 其他一切都是真实的。


In your example: [1, 2] or ["hello"] == [1, 2] because the first element, [1, 2 is Truthy (the fact that ["hello"] is also Truthy is irrelevant in this case). 在您的示例中: [1, 2] or ["hello"] == [1, 2]因为第一个元素[1, 2是Truthy(在这种情况下["hello"]也是Truthy的事实是不相关的)。 Note that [1, 2] and ["hello"] == ["hello"] . 请注意[1, 2] and ["hello"] == ["hello"]

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

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