#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2012
    Posts
    1
    Rep Power
    0

    Search the list of objects


    Hello,

    A python newbie here. I have a list of objects each carrying a number of different pieces of data (each object has a a couple of strings, and a whole bunch of parameter values stored in it). I am looking for an efficient way to search through this list of objects to find all the members with a given value for a certain parameter of interest. Basically, I would like to go through the list, call a function that returns the value of the parameter of interest stored inside, and then evaluate if that value is what I am looking for.

    So far, I have been creating another 'index' list by, first, looping through my list of objects and adding the values of the parameter of interest for each object to the 'index' list. Then using something like

    if x in indexlist: ind = indexlist.index(x)

    But, I am hoping there is another way to search my list directly without generating another list.

    Thanks a lot and sorry to be so verbose
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481
    Alternatives are filter which is builtin or from itertools, or you can use list comprehension. Illustrated list comprehension:
    Code:
    import re
    import pprint
    
    class c:
    
        def __init__(self,**kwargs):
            self._kwargs = kwargs
    
        def __getattr__(self,attr):
            try:
                return self._kwargs[attr]
            except KeyError:
                raise AttributeError(attr)
    
        def __str__(self):
            return pprint.pformat(self._kwargs)
    
    LIST = [c(a=1,b=2,c='behold'),c(b=28,a=2,c='the'),c(a={1,2,3},b=8,c='sea')]
    
    print('objects where b is less than 10:')
    print('\n'.join(str(o) for o in LIST if o.b < 10))
    
    print("\nobjects for which attribute c contains 'h'")
    search = re.compile('h').search
    print('\n'.join(str(o) for o in LIST if search(o.c)))
    
    print('\nobjects where type of a is set:')
    print('\n'.join(str(o) for o in LIST if type(o.a) == type(set())))
    Last edited by b49P23TIvg; August 16th, 2012 at 11:35 AM. Reason: Correction: change index error to key error.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,856
    Rep Power
    481

    Extended idea, see the __eq__ method


    Code:
    import re
    import pprint
    
    class c:
    
        def __init__(self,**kwargs):
            self._kwargs = kwargs
    
        def __getattr__(self,attr):
            try:
                return self._kwargs[attr]
            except IndexError:
                raise AttributeError(attr)
    
        def __str__(self):
            return pprint.pformat(self._kwargs)
    
    
        #Another idea: put a proxy __eq__ method into your class that
        #you preset for which attribute to compare,
        #and then you could use straightforward list indexing.
    
        attribute = 'c'
    
        def __eq__(self,value):
            attribute = self.__class__.attribute
            try:
                return getattr(self,attribute) == value
            except:
                return False
    
        def __req__(self,value):
            return self == value
    
    #    def __contains__(self,item):  # support the "in" operator
    #        # something
    
    
    LIST = [c(a=1,b=2,c='behold'),c(b=28,a=2,c='the'),c(a={1,2,3},b=8,c='sea')]
    
    print('objects where b is less than 10:')
    print('\n'.join(str(o) for o in LIST if o.b < 10))
    
    print("\nobjects for which attribute c contains 'h'")
    search = re.compile('h').search
    print('\n'.join(str(o) for o in LIST if search(o.c)))
    
    print('\nobjects where type of a is set:')
    print('\n'.join(str(o) for o in LIST if type(o.a) == type(set())))
    
    
    print('\nusing indexing, a is 2')
    c.attribute = 'a'
    print(str(LIST[LIST.index(2)]))
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo