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

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

    I will have a preference for:

    itertools.ifilter(bool, (expensive(x) for x in mylist))
    

    This has the advantage to:

    • avoid None as the function (will be eliminated in Python 3): http://bugs.python.org/issue2186
    • use only iterators.

提交回复
热议问题