I have a list which contains a number of things:
lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2
. Is there a neater way to do it than itertools' dropwhile and next?
first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista))
I did use [item for item in lista if len(item)>2][0]
at first, but that requires python to generate the entire list first.
>>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
>>> next(i for i in lista if len(i) > 2)
'foo'
精彩评论