不为空的变量的返回值

编程入门 行业动态 更新时间:2024-10-23 19:29:40
本文介绍了不为空的变量的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

python 中返回 3 个变量的值的最佳方法是什么,即不为 ​​null.任何时候只有 1 个变量不会为空.

what is the best way in python to return the value of 3 variables, that is not null. only 1 of the variable will not be null at any time.

到目前为止,我使用的是这种低效的代码

so far i am using this non efficient code

if kwargs.get('F06_yes_1'): context1.update({'F06_1': kwargs['F06_yes_1']}) elif kwargs.get('F06_no_1'): context1.update({'F06_1': kwargs['F06_no_1']}) else: context1.update({'F06_1': kwargs['F06_na_1']})

此外,要进行替换(根据您的评论),您可以尝试:

Furthermore, to do the replacement (based on your comments), you can try:

context1.update({ 'F06_1': ('yes' if kwargs['F06_yes_1'] else None) or ('no' if kwargs['F06_no_1'] else None) or ('n/a' if kwargs['F06_na_1'] else None) })

对于下面提供的答案,当 F06_yes_1 值为空且 F06_no_1 值为on"时,我收到以下错误:

further to the answer provided below, when F06_yes_1 value is null, and F06_no_1 value is "on" i get the following error:

Traceback (most recent call last): File "C:\Python27\lib\site-packages\cherrypy\_cprequest.py", line 670, in respond response.body = self.handler() File "C:\Python27\lib\site-packages\cherrypy\lib\encoding.py", line 217, in __call__ self.body = self.oldhandler(*args, **kwargs) File "C:\Python27\lib\site-packages\cherrypy\_cpdispatch.py", line 60, in __call__ return self.callable(*self.args, **self.kwargs) File "example.py", line 872, in RPC_submit 'F06_1': ('yes' if kwargs['F06_yes_1'] else None) KeyError: 'F06_yes_1'

推荐答案

or 操作将选择第一个非 None 值.

The or operation will select the first non-None value.

context1.update({ 'F06_1': kwargs['F06_yes_1'] or kwargs['F06_no_1'] or kwargs['F06_na_1'] })

此外,要进行替换(根据您的评论),您可以尝试:

Furthermore, to do the replacement (based on your comments), you can try:

context1.update({ 'F06_1': ('yes' if kwargs.get('F06_yes_1', None) else None) or ('no' if kwargs.get('F06_no_1', None) else None) or ('n/a' if kwargs.get('F06_na_1', None) else None) })

您收到 KeyError 是因为您试图查找不存在的记录.为了更优雅地处理这个问题,您可以使用带有第二个参数的 .get 方法,如果键不存在,该方法将作为默认返回值.

You're getting the KeyError because you're trying to lookup a record that doesn't exist. To handle this more elegantly, you can use the .get method with a second argument which acts as the default return value if the key doesn't exist.

更多推荐

不为空的变量的返回值

本文发布于:2023-11-26 18:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   为空   返回值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!