Using 'in' to match an attribute of Python objects in an array

后端 未结 8 1547
傲寒
傲寒 2021-01-07 16:25

I don\'t remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,

foo in iter_attr(array of python ob         


        
8条回答
  •  灰色年华
    2021-01-07 16:28

    Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search.

    The temporary list can be avoiding by using a generator expression:

    foo = 12
    foo in (obj.id for obj in bar)
    

    Now, as long as obj.id == 12 near the start of bar, the search will be fast, even if bar is infinitely long.

    As @Matt suggested, it's a good idea to use hasattr if any of the objects in bar can be missing an id attribute:

    foo = 12
    foo in (obj.id for obj in bar if hasattr(obj, 'id'))
    

提交回复
热议问题