gpt4 book ai didi

python - 抽象 if 语句并通过函数返回

转载 作者:行者123 更新时间:2023-12-01 04:40:21 28 4
gpt4 key购买 nike

我有一个这样的函数:

def test():
x = "3" # In actual code, this is computed

if x is None:
return None

y = "3"

if y is None:
return None

z = "hello"

if z is None:
return None

有没有办法让 if 语句消失并用一些函数抽象它。我期待这样的事情:

def test():
x = "3"
check_None(x)

y = "3"
check_None(y)

z = "hello"
check_None(z)

理想情况下,如果传递给它的参数为 None,则 check_None 应更改控制流。这可能吗?

注意:使用 Python 2.7。

最佳答案

您可以轻松地用这样的代码进行编码。

def test():
#compute x, y, z
if None in [x, y, z]:
return None
# proceed with rest of code

更好的方法是使用生成器生成值 x、y、z,以便一次只计算一个值。

def compute_values():
yield compute_x()
yield compute_y()
yield compute_z()

def test():
for value in compute_values():
if value is None:
return None

关于python - 抽象 if 语句并通过函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818718/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com