模仿 javascript || 的 Python 运算符运算符(operator)

标签 python

我是 Python 新手,所以可能不知道这是否显而易见。

在 Javascript a||b 中,如果 a 的计算结果为真,则返回 a,否则返回 b。 除了冗长的 if else 语句之外,这在 Python 中是否可能。

最佳答案

我相信这是正确的:

x = a or b

证明

这就是“||”在 JavaScript 中的工作方式:

> 'test' || 'again'
"test"
> false || 'again'
"again"
> false || 0
0
> 1 || 0
1

这是“or”在 Python 中的工作方式:

>>> 'test' or 'again'
'test'
>>> False or 'again'
'again'
>>> False or 0
0
>>> 1 or 0
1

关于模仿 javascript || 的 Python 运算符运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8111484/

相关文章:

python - 如何将数据框旋转为方形数据框,并将其他列中的交集数作为值

python - ctypes.pointer、ctypes.POINTER 和 ctypes.byref 之间有什么区别?

基础对象更改时的Python迭代器

python - 从掩模计算图像的一部分的共现矩阵

python - 从 python 向带有 windows-1251 编码的页面发送请求

python - Pandas 多个条件下行之间的差异

python - 如何使用子进程与 python 脚本交互

python - 如何在Python中使用turtle模块播放GIF?

python - Airflow Unittest.cfg 权限问题?

Python 多处理负载均衡器