将if语句的条件赋给一个变量。

huangapple go评论53阅读模式
英文:

assign the condition of the if statement to a variable

问题

我有一段很长的代码片段,我正在尝试缩短它。 现在我有这样的代码:

statuses = cleaned_data.get("statuses")
if statuses:
    for status in statuses:
        ...

如果我可以在if条件内赋值cleaned_data.get("statuses")的值,就会很好,就像这样:

if cleaned_data.get("statuses") as statuses

然后继续执行。这在Python中可行吗?

英文:

I have a long snippet of code and i am trying to shorten it.
This is what I have now:

statuses = cleaned_data.get("statuses")
if statuses:
    for status in statuses:
        ...

it would be nice if i can assign the value of cleaned_data.get("statuses") inside the if condition, like this:
if cleaned_data.get("statuses") as statuses
and carry on.
Is it doable in python?

答案1

得分: 1

你可以使用赋值表达式(也称为海象运算符)

if statuses := cleaned_data.get("statuses"):
    for status in statuses:
英文:

You can use Assignment Expression (a.k.a walrus operator):

if statuses := cleaned_data.get("statuses"):
    for status in statuses:

huangapple
  • 本文由 发表于 2023年3月8日 18:24:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定