我是 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/