[英]Evaluation of function in python list comprehension action step and condition at the same time
我对以下代码中的 python 感兴趣。
def test_func(a: str) -> str or None:
# Just example
if a.endswith("r"):
return f"{a}rr"
elif a.endswith("s"):
return None
else:
return a
if __name__=="__main__":
...
source_list = ["Edgar", "Pedros", "Alexander"]
test = [test_func(x) for x in source_list if test_func(x)]
我的问题是 python 如何应对test_func(x)
function 的评估。 是完成两次还是 python 能够识别出可以在两个地方使用相同的结果并且只评估一次 function? :-)
它对真值为真的元素调用test_func(x)
两次(对真值为假的元素调用一次)。 如果你只想在所有情况下调用一次,你可以这样做:
test = [v for v in (test_func(x) for x in source_list) if v]
除非您存储 function 结果,否则一旦您编写带有一对括号的 function 名称,就会发生对 function 的新调用
哈,所以我只是在 function 中添加了一个打印语句,它已经显示出来了。
答案是,如果条件被评估为正,则 function 会被评估两次。 这是我的例子:
>>> def test(a: str) -> str or None:
... print(f"HERE {a}")
... if a.endswith("r"):
... return f"{a}rr"
... elif a.endswith("s"):
... return None
... else:
... return a
...
>>> source = ["Edgar", "Pedros", "Alexander"]
>>> [test(x) for x in source if test(x)]
HERE Edgar
HERE Edgar
HERE Pedros
HERE Alexander
HERE Alexander
如果您使用的是 Python 3.8+,则可以使用非常适合此操作的walrus 运算符!
test = [tested for x in source_list if (tested := test_func(x))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.