简体   繁体   English

Python条件变量赋值

[英]Python conditional variable assignment

Morning all, 大家早,

Can someone advise, is it possible to achieve something like this: 有人可以建议,是否有可能实现这样的目标:

def myFunction(someParam)
   if someParam == 1:
      return "This and that"
   else:
      return None

someVariable = someVariable || myFunction(valuePassedIn)

ie, given "someVariable" has an existing value, I want to preserve that value, or replace it with the value returned from "myFunction", provided that is not None? 即,给定“someVariable”具有现有值,我想保留该值,或者用“myFunction”返回的值替换它,前提是它不是None?

Obviously, I can do something like: 显然,我可以这样做:

if myFunction(valuePassedIn) != None:
    someVariable = myFunction(valuePassedIn)

But this of course is calling myFunction twice. 但这当然是两次调用myFunction。 Alternatively, I could do: 或者,我可以这样做:

myFuncRes = myFunction(valuePassedIn)
if MyFuncRes != None:
    someVariable = myFuncRes

But it'd be good if I could reduce this to a single line of code, as per my "||" 但是,根据我的“||”,如果我可以将其减少到一行代码就好了。 line in the first code snippet above. 在上面的第一个代码段中的行。 Obviously I've seen the conditional expressions documentation , but unless I'm misunderstanding, this would still involve calling myFunction twice? 显然我已经看过条件表达式文档 ,但除非我误解,否则这仍然需要调用myFunction两次?

I guess one other option would be to pass someVariable in as an additional param to myFunction and use this as the "else" return instead of None, but I can't help feeling this is kinda messy - and Python probably has something more slick I could use? 我猜另外一个选择是将someVariable作为额外的参数传递给myFunction并使用它作为“else”返回而不是None,但我不禁觉得这有点乱 - 而Python可能有更多的光滑我可以用?

Thanks 谢谢

Yes you can do this 是的,你可以这样做

Please check below code 请检查以下代码

>>> a = 1
>>> def test(b):
...     return b*10
...
>>> c = a or test(2)
>>> c
1
>>> a = 0
>>> c = a or test(2)
>>> c
20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM