Python:Inline if语句else什么也不做 [英] Python: Inline if statement else do nothing

查看:6733
本文介绍了Python:Inline if语句else什么也不做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果匹配条件,则将Django模型的字段分配给值。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆