The following code is efficient, flexible, and concise when exploring target_list linearly.
next(( {x} for {x} in {target_list} if {condition} ),None)
The second variable is the value returned if not found.
By using next, it is possible to fetch the first one among the conditions, which is efficient.
Example
class Hoge(object):
def __init__(self,x,y):
self.x=x
self.y=y
hoge_list=[Hoge(10,20),Hoge(10,30),Hoge(5,3),...]
found=next( (hoge for hoge in hoge_list if hoge.x==10 and hoge.y==30) ,None)
reference http://dev.ionous.net/2009/01/python-find-item-in-list.html
Recommended Posts