Sequence find function in Python

后端 未结 4 416
生来不讨喜
生来不讨喜 2020-12-15 04:20

How do I find an object in a sequence satisfying a particular criterion?

List comprehension and filter go through the entire list. Is the only alternative a handmade

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 05:01

    Actually, in Python 3, at least, filter doesn't go through the entire list.

    To double check:

    def test_it(x):
        print(x)
        return x>10
    
    var = next(filter(test_it, range(20)))
    

    In Python 3.2, that prints out 0-11, and assigns var to 11.

    In 2.x versions of Python you may need to use itertools.ifilter.

提交回复
热议问题