gpt4 book ai didi

python - Python if 语句中赋值

转载 作者:行者123 更新时间:2023-12-01 04:43:18 25 4
gpt4 key购买 nike

有没有比这个更简单的替代方案

res = returns_value_or_none(arg)
if res:
do_something_with(res)

if returns_value_or_none(arg):
do_something_with(returns_value_or_none(arg))

将赋值和 if 条件组合到一个语句中的一个?

最佳答案

对于 Python 3.8+,PEP 572引入赋值表达式

这允许使用符号NAME := expr为表达式中的变量赋值。它可以在 if 语句中使用,例如:

if (match := pattern.search(data)) is not None:
# Do something with match

关于python - Python if 语句中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30066516/

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