Python 中 NOT、AND、OR 逻辑运算符的优先级(运算顺序)
- 2024-12-30 08:42:00
- admin 原创
- 107
问题描述:
据我所知,在 C 和 C++ 中,NOT AND 和 OR 的优先级顺序为 NOT>AND>OR。但这在 Python 中似乎不起作用。我尝试在 Python 文档中搜索它,但失败了(我想我有点不耐烦。)。有人能帮我澄清一下吗?
解决方案 1:
根据运算符优先级的文档,从高到低
依次为NOT
,,,AND
`OR`
以下是完整的优先级表,优先级从低到高。一行具有相同的优先级,并从左到右分组
0. :=
1. lambda
2. if – else
3. or
4. and
5. not x
6. in, not in, is, is not, <, <=, >, >=, !=, ==
7. |
8. ^
9. &
10. <<, >>
11. +, -
12. *, @, /, //, %
13. +x, -x, ~x
14. **
14. await x
15. x[index], x[index:index], x(arguments...), x.attribute
16. (expressions...), [expressions...], {key: value...}, {expressions...}
解决方案 2:
您可以进行以下测试来找出and
和的优先级or
。
首先,0 and 0 or 1
在 python 控制台中尝试
如果or
先绑定,那么我们期望0
输出。
在我的控制台中,1
是输出。这意味着and
要么先绑定,要么等于or
(表达式可能从左到右求值)。
那就尝试一下1 or 0 and 0
。
如果or
和and
与内置的从左到右评估顺序同样绑定,那么我们应该得到0
输出。
在我的控制台中,1
是输出。然后我们可以得出结论,and
优先级高于or
。
解决方案 3:
not
绑定比语言参考中所述and
的绑定更紧密or
解决方案 4:
布尔运算符的优先级从弱到强如下:
or
and
not x
is not
;not in
当运算符具有相同的优先级时,计算从左到右进行。
解决方案 5:
一些简单的例子;注意运算符优先级(非、与、或);括号有助于人类的可解释性。
a = 'apple'
b = 'banana'
c = 'carrots'
if c == 'carrots' and a == 'apple' and b == 'BELGIUM':
print('True')
else:
print('False')
# False
相似地:
if b == 'banana'
True
if c == 'CANADA' and a == 'apple'
False
if c == 'CANADA' or a == 'apple'
True
if c == 'carrots' and a == 'apple' or b == 'BELGIUM'
True
# Note this one, which might surprise you:
if c == 'CANADA' and a == 'apple' or b == 'banana'
True
# ... it is the same as:
if (c == 'CANADA' and a == 'apple') or b == 'banana':
True
if c == 'CANADA' and (a == 'apple' or b == 'banana'):
False
if c == 'CANADA' and a == 'apple' or b == 'BELGIUM'
False
if c == 'CANADA' or a == 'apple' and b == 'banana'
True
if c == 'CANADA' or (a == 'apple' and b == 'banana')
True
if (c == 'carrots' and a == 'apple') or b == 'BELGIUM'
True
if c == 'carrots' and (a == 'apple' or b == 'BELGIUM')
True
if a == 'apple' and b == 'banana' or c == 'CANADA'
True
if (a == 'apple' and b == 'banana') or c == 'CANADA'
True
if a == 'apple' and (b == 'banana' or c == 'CANADA')
True
if a == 'apple' and (b == 'banana' and c == 'CANADA')
False
if a == 'apple' or (b == 'banana' and c == 'CANADA')
True
解决方案 6:
Python没有理由采用与(几乎)所有其他编程语言(包括 C/C++)中已确立的优先级顺序不同的运算符优先级顺序。
你可以在《Python 语言参考》第 6.16 部分 - 运算符优先级中找到它,可从https://docs.python.org/3/download.html下载(当前版本并包含所有其他标准文档),或者在这里在线阅读:6.16。运算符优先级。
但是 Python 中仍有一些东西可能会误导您:and运算符的结果可能与or不同- 请参阅同一文档中的6.11 布尔运算。and
`orTrue
False`
解决方案 7:
not
>and
print(~0&0) # 0
and
>or
print(0&0|1) # 1