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

后端 未结 8 1541
傲寒
傲寒 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:31

    The function you are thinking of is probably operator.attrgettter. For example, to get a list that contains the value of each object's "id" attribute:

    import operator
    ids = map(operator.attrgetter("id"), bar)

    If you want to check whether the list contains an object with an id == 12, then a neat and efficient (i.e. doesn't iterate the whole list unnecessarily) way to do it is:

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

    If you want to use 'in' with attrgetter, while still retaining lazy iteration of the list:

    import operator,itertools
    foo = 12
    foo in itertools.imap(operator.attrgetter("id"), bar)
    

提交回复
热议问题