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

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

    Are you looking to get a list of objects that have a certain attribute? If so, a list comprehension is the right way to do this.

    result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]
    
    0 讨论(0)
  • 2021-01-07 16:52

    you could always write one yourself:

    def iterattr(iterator, attributename):
        for obj in iterator:
            yield getattr(obj, attributename)
    

    will work with anything that iterates, be it a tuple, list, or whatever.

    I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.

    0 讨论(0)
提交回复
热议问题