问题
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