Python list comprehension - want to avoid repeated evaluation

前端 未结 12 2307
被撕碎了的回忆
被撕碎了的回忆 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:14

    Use map() !!

    comp = [x for x in map(f, l) if x]
    

    f is the function f(X), l is the list

    map() will return the result of f(x) for each x in the list.

提交回复
热议问题