簡體   English   中英

python列表理解動作步驟和條件中的function同時評價

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM