Python:Inline if语句else什么也不做 [英] Python: Inline if statement else do nothing
问题描述
g = Car.objects.get(pk = 1234)
g.data_version = my_dict ['dataVersion'] if my_dict else expression_false#什么也不做?
在这种情况下,我该怎么办?
我知道我可以做的:
如果my_dict:
g.data_version = my_dict ['dataVersion']
但是我想知道是否有一种方法可以内联 expression_true,如果条件其他什么都不做任何
。
不,你不能完全按照你所描述的方式做,因为没有意义。您正在分配变量 g.data_version
...所以你必须分配一些东西。你所描述的就像写作:
g.data_version =#这里没有别的
哪个显然是无效的语法。真的,没有理由这样做。你应该做:
if my_dict:
g.data_version = my_dict ['dataVersion']
或
g.data_version = my_dict ['dataVersion'] if my_dict else无#或0或取决于什么data_version应该是。
从技术上讲,您还可以:
g.data_version = my_dict ['dataVersion'] if my_dict else g.data_version
如果您只想更新 g.data_version
,如果您的dict存在,但这比使用正常的if语句更不可读和优雅。
Assigning a Django Model's field to a value if it matches a condition.
g = Car.objects.get(pk=1234)
g.data_version = my_dict['dataVersion'] if my_dict else expression_false # Do nothing??
How do I do nothing in that case? We can't do if conditional else pass
.
I know I can do:
if my_dict:
g.data_version = my_dict['dataVersion']
but I was wondering if there was a way to do inline expression_true if conditional else do nothing
.
No, you can't do exactly what you are describing, as it wouldn't make sense. You are assigning to the variable g.data_version
... so you must assign something. What you describe would be like writing:
g.data_version = # There is nothing else here
Which is obviously invalid syntax. And really, there's no reason to do it. You should either do:
if my_dict:
g.data_version = my_dict['dataVersion']
or
g.data_version = my_dict['dataVersion'] if my_dict else None # or 0 or '' depending on what data_version should be.
Technically, you could also do:
g.data_version = my_dict['dataVersion'] if my_dict else g.data_version
if you only want to update g.data_version
if your dict exists, but this is less readable and elegant than just using a normal if statement.
这篇关于Python:Inline if语句else什么也不做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!