python 操作符优先级

使用python时遇到的运算符优先级问题

以下代码在list_2为空时返回else后面的值,若期望在list_2为空时返回if后面的值,则需要使用括号。

1
2
3
4
5
6
7
8
>>> list_1 = [1, 2, 3]
>>> list_2 = list()
>>> value = list_1 + list_2 if list_2 else ["a", "b"]
>>> value
['a', 'b']
>>> value = list_1 + (list_2 if list_2 else ["a", "b"])
>>> value
[1, 2, 3]

操作符优先级说明-摘自官方文档

Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.

All comparison operators have the same priority, which is lower than that of all numerical数字的 operators.

Boolean operators and, or and not have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C. As always, parentheses can be used to express表示 the desired composition作文,构成,成份.

Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus海象 operator :=

1
2
3
4
5
6
7
8
>>> if a := "wsx":
... print(a)
...
wsx
>>> if a := "":
... print(a)
...
>>>

python 操作符优先级
https://www.tao-wt.fun/python/operator/
作者
tao-wt@qq.com
发布于
2023年12月17日
许可协议