Python:内联if语句别无效
Assigning a Django Model's field to a value if it matches a condition.
如果Django Model的字段与条件匹配,则将其分配给值。
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
.
但我想知道是否有一种方法可以做内联expression_true如果条件别做什么都不做。
1 个解决方案
#1
8
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_version
if your dict exists, but this is less readable and elegant than just using a normal if statement.
如果您只想更新g.data_version,如果您的dict存在,但这比仅使用普通的if语句更不易读和优雅。
更多相关文章
- numpy无法将值分配给列的一部分
- Python基础 条件判断和循环
- Python3 基础:条件判断和循环&三元运算符
- Linux进程通信[2]-互斥锁和条件变量
- gdb捕获syscall条件和字符串比较
- SQL查找条件语句构造类
- qt sql多重条件查询简便方法
- 如何在一个查询中组合六个独立查询。表是单一的,但条件不同
- sql 存储过程参数为空则不作为条件