Python:内联 if 语句 else 什么都不做
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25319053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Inline if statement else do nothing
提问by user1757703
Assigning a Django Model's field to a value if it matches a condition.
如果匹配条件,则将 Django 模型的字段分配给一个值。
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.
在这种情况下,我怎么什么都不做?我们做不到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.
但我想知道是否有办法进行内联expression_true if conditional else do nothing。
采纳答案by Johndt6
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......所以您必须分配一些东西。你所描述的就像写:
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_versionif your dict exists, but this is less readable and elegant than just using a normal if statement.
如果您只想更新g.data_version您的 dict 是否存在,但这比仅使用普通的 if 语句可读性和优雅性较差。

