Return value of variables that is not null

懵懂的女人 提交于 2019-12-13 20:16:37

问题


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)
})

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'

回答1:


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)
}) 

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.



来源:https://stackoverflow.com/questions/46292549/return-value-of-variables-that-is-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!