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

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

    The most obvious (and I would argue most readable) answer is to not use a list comprehension or generator expression, but rather a real generator:

    def gen_expensive(mylist):
        for item in mylist:
            result = expensive(item)
            if result:
                yield result
    

    It takes more horizontal space, but it's much easier to see what it does at a glance, and you end up not repeating yourself.

提交回复
热议问题