python - 在 if 语句中使用别名

标签 python if-statement alias

Python 中有没有一种方法可以使用函数结果作为 if 语句的测试和语句内的值? 我的意思是:

if f(x) as value:
   # Do something with value

不是

value = f(x)
if value:
   # Do something with value

with f(x) as value:
   if value:
       # Do something with value

最佳答案

是的,从 python3.8 及更高版本开始,有。通过使用有争议的 walrus(:=) 运算符,例如,

$ python3.8
Python 3.8.0 (default, Oct 15 2019, 11:27:32) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x): return x
... 
>>> if value := f(1):
...   print(value)
... 
1
>>> if value := f(0):
...   print(value) # won't execute
... 
>>> 

关于python - 在 if 语句中使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58724761/

相关文章:

python - peewee 的 get 方法如何知道如何生成 where 子句?

javascript - jQuery 多个 else if 语句

python - 在 python 中返回 "for if in"语句

linux - 是否可以为字符串设置别名?

mysql - 从此 SQL 查询中删除变量(子查询帮助)

python - 从数据集中提取文本

python - 处理 pandas Dataframe 中的特殊字符作为列名

database - Sharepoint 2010 数据库 - 如何从 SQL 2012 AlwaysOn 迁移到独立 SQL 2012

python - 程序不能作为单一且无控制台的 exe 文件运行(Pyinstaller)

linux - 通过 If 语句判断数值是否超出范围