Python list comprehension - want to avoid repeated evaluation

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

    You should use a memoize decorator. Here is an interesting link.


    Using memoization from the link and your 'code':

    def memoize(f):
        """ Memoization decorator for functions taking one or more arguments. """
        class memodict(dict):
            def __init__(self, f):
                self.f = f
            def __call__(self, *args):
                return self[args]
            def __missing__(self, key):
                ret = self[key] = self.f(*key)
                return ret
        return memodict(f)
    
    @memoize
    def f(x):
        # your code
    
    [f(x) for x in l if f(x)]
    

提交回复
热议问题