英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论