gpt4 book ai didi

python - Python 逻辑表达式中的奇怪转换

转载 作者:太空狗 更新时间:2023-10-29 22:13:34 25 4
gpt4 key购买 nike

我注意到 Python 2.7 逻辑表达式的一个奇怪行为:

>>> 0 and False0>>> False and 0False>>> 1 and FalseFalse>>> False and 1False

用 True 代替 False

>>> 0 and True0>>> True and 00>>> 1 and TrueTrue>>> True and 11

Python将逻辑语句转换为整数有什么规则吗?为什么有时会显示 0 insted of False 和 1 insted of True?

还有,为什么会返回这个?

>>>"test" or "test"'test'

最佳答案

没有任何内容被转换; Python bool 逻辑运算符而不是短路

参见 boolean operators documentation :

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

此外,等于 0 的数字被认为是错误的,空字符串和容器也是如此。引用同一文档:

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).

结合这两种行为意味着对于 0 和 False0认为为 false 并在评估 False< 之前返回 表达式。对于表达式 True and 0,计算 True 并发现其为真值,因此返回 0。就 ifwhile 以及其他 bool 运算符而言,结果 0 也被视为 false。

您可以使用它来提供默认值,例如:

foo = bar or 'default'

要真正将非 bool 值转换为 bool 值,请使用 bool() type ;它使用与 bool 表达式相同的规则来确定输入的 bool 值:

>>> bool(0)
False
>>> bool(0.0)
False
>>> bool([])
False
>>> bool(True and 0)
False
>>> bool(1)
True

为了完成图片,在 bool 上下文中不被视为假的值被视为真,包括任何自定义类。您可以通过实现 .__nonzero__() special method 来更改它在你的课上。如果没有定义这样的方法,.__len__()也被咨询。使用这些方法中的任何一种,您都可以表示您的类型是数字,如果非零则应被视为 True,或者它是一个容器,如果不是则应被视为 True空(长度超过 0)。

关于python - Python 逻辑表达式中的奇怪转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com