gpt4 book ai didi

Python 相当于 PHP 的空合并运算符和速记三元运算符?

转载 作者:太空宇宙 更新时间:2023-11-03 14:52:22 24 4
gpt4 key购买 nike

我正在寻找这里但找不到任何东西:https://docs.python.org/3/library/operator.html

两个非常有用的 PHP 示例:

echo $count ?: 10; //prints $count if $count is not empty string, null, false or 0, otherwise prints 10.

echo $a ?? $b ?? 7; //prints $a if $a is defined and not null, otherwise will print $b, otherwise 7

Python 中是否有等效的运算符?注意:

a if condition else b

并没有真正取代速记三元运算符,因为在速记版本的 PHP 中,条件和返回值是在一个元素中指定的。

最佳答案

or 运算符返回第一个 truth-y 值。

a = 0
b = None
c = 'yep'

print(a or 'nope')
print(b or 'nope')
print(c or 'nope')
print(b or c or 'nope')
> nope
> nope
> yep
> yep

关于Python 相当于 PHP 的空合并运算符和速记三元运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45012357/

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