Python list comprehension - want to avoid repeated evaluation

前端 未结 12 2278
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 05:23

I have a list comprehension which approximates to:

[f(x) for x in l if f(x)]

Where l is a list and f(x) is an expensive function which retu

12条回答
  •  死守一世寂寞
    2020-11-27 06:12

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to use a local variable within a list comprehension in order to avoid calling twice the same function:

    In our case, we can name the evaluation of f(x) as a variable y while using the result of the expression to filter the list but also as the mapped value:

    [y for x in l if (y := f(x))]
    

提交回复
热议问题