简体   繁体   English

python列表理解动作步骤和条件中的function同时评价

[英]Evaluation of function in python list comprehension action step and condition at the same time

I am interested in what does python under the hood in the following code.我对以下代码中的 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)]

My question here is how python under the hood copes with the evaluation of the test_func(x) function.我的问题是 python 如何应对test_func(x) function 的评估。 Is it done twice or python is able to recognize that the same result can be used on both places and evaluates the function only once?是完成两次还是 python 能够识别出可以在两个地方使用相同的结果并且只评估一次 function? :-) :-)

It calls test_func(x) twice for elements for which its truth value is true (and once for those whose truth value is false).它对真值为真的元素调用test_func(x)两次(对真值为假的元素调用一次)。 If you only want to call it once in all cases, you can do:如果你只想在所有情况下调用一次,你可以这样做:

test = [v for v in (test_func(x) for x in source_list) if v]

unless you store function results, as soon as you write a function name with pair of parenthesis new call to the function occur除非您存储 function 结果,否则一旦您编写带有一对括号的 function 名称,就会发生对 function 的新调用

Hah, so I just add there a print statement to the function and it has revealed itself.哈,所以我只是在 function 中添加了一个打印语句,它已经显示出来了。

The answer is that in case the condition is evaluated as positive the function is evaluated twice.答案是,如果条件被评估为正,则 function 会被评估两次。 Here is my example:这是我的例子:

>>> 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

If you're using Python 3.8+, you can use the walrus operator which is perfect for this!如果您使用的是 Python 3.8+,则可以使用非常适合此操作的walrus 运算符

test = [tested for x in source_list if (tested := test_func(x))]

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

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