开发者

Is there a neater way to get the first occurrence of something?

开发者 https://www.devze.com 2022-12-29 05:59 出处:网络
开发者_运维技巧I have a list which contains a number of things: lista = [\'a\', \'b\', \'foo\', \'c\', \'d\', \'e\', \'bar\']
开发者_运维技巧

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'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号