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.
更多推荐
不为空的变量的返回值
发布评论