Sequence find function in Python

后端 未结 4 405
生来不讨喜
生来不讨喜 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 04:58

    If you only want the first greater than 10 you can use itertools.ifilter:

    import itertools
    first_gt10 = itertools.ifilter(lambda x: x>10, [10, 2, 20, 5, 50]).next()
    

    If you want all greater than 10, it may be simplest to use a list-comprehension:

    all_gt10 = [i for i in mylist if i > 10]
    

提交回复
热议问题