sách gpt4 ai đã đi

Tóm tắt câu lệnh if và trả về thông qua hàm

In lại 作者:行者123 更新时间:2023-12-01 04:40:21 30 4
mua khóa gpt4 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

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

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

y = "3"
check_None(y)

z = "hello"
check_None(z)

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

注意:使用 Python 2.7。

1 Câu trả lời

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

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/

30 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com