[英]How to avoid duplicating function call in the IF check and return statement if the condition evaluates to true?
I have a function process
.我有一个函数process
。 If attempts to retrieve one of name, address, phone from the input data (in that order) using their own functions which either return the appropriate value or return ''.如果尝试使用它们自己的函数从输入数据中检索姓名、地址、电话之一(按该顺序),这些函数要么返回适当的值,要么返回 ''。 If all return '' then return the data as it is.如果都返回 '' 则按原样返回数据。
Following is the code, is there a better way to avoid duplicating function invocations in both if check and return?以下是代码,是否有更好的方法来避免在 if check 和 return 中重复函数调用?
def process(data):
if get_name(data):
return get_name(data)
elif get_address(data):
return get_address(data)
elif get_phone(data):
return get_phone(data)
return data
As per your code logic, you can write it like this.根据你的代码逻辑,你可以这样写。 The or
sequence will return the first positive data, in other words the data that is truthy
. or
序列将返回第一个正数据,换句话说,就是truthy
的数据。
def process(data):
name = get_name(data)
address = get_address(data)
phone = get_phone(data):
return name or address or phone or data
You can use walrus operator :=
if you use python 3.8+如果你使用 python 3.8+,你可以使用 walrus operator :=
def process(data):
if name:=get_name(data):
return name
elif address := get_address(data):
return address
elif phone := get_phone(data):
return phone
return data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.