How do I efficiently filter computed values within a Python list comprehension?

后端 未结 9 2358
青春惊慌失措
青春惊慌失措 2020-12-15 05:29

The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:

result = [x**2 for x in mylist if type(x) is int]
<         


        
9条回答
  •  爱一瞬间的悲伤
    2020-12-15 06:33

    You could always memoize the expensive() function so that calling it the second time around is merely a lookup for the computed value of x.

    Here's just one of many implementations of memoize as a decorator.

提交回复
热议问题