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

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

    Came up with my own answer after a minute of thought. It can be done with nested comprehensions:

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

    I guess that works, though I find nested comprehensions are only marginally readable

提交回复
热议问题