search - Python: Find the position in a list of the first object that respect a given condition -
i have list of following kind:
class any(object): def __init__(self,a,b): self.a=a self.b=b l=[any(1,3),any(2,4),any(1,2),any(none,6),any('hello',6), any(1,'chucknorris'),any(1,2)] lis list contains instances of any. i'd find position of first of these instances attribute a equals 'none`.
as list long, algorithm should not explore whole list should stop condition (in example, attribute a equals none) found.
in above example answer of algorithm should 3.
use generator expression , next:
next((i i, item in enumerate(l) if item.a none), none) this return none if no such item found.
demo:
>>> l=[any(1,3),any(2,4),any(1,2),any(none,6),any('hello',6), any(1,'chucknorris'),any(1,2)] >>> next((i i, item in enumerate(l) if item.a none), none) 3
Comments
Post a Comment