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

后端 未结 9 2357
青春惊慌失措
青春惊慌失措 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:19

    result = [x for x in map(expensive,mylist) if x]
    

    map() will return a list of the values of each object in mylist passed to expensive(). Then you can list-comprehend that, and discard unnecessary values.

    This is somewhat like a nested comprehension, but should be faster (since the python interpreter can optimize it fairly easily).

提交回复
热议问题