Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old August 16th, 2012, 09:35 AM
4izhik 4izhik is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2012
Posts: 1 4izhik User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 11 m 53 sec
Reputation 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

Reply With Quote
  #2  
Old August 16th, 2012, 11:33 AM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,458 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 4 Days 6 h 26 m 43 sec
Reputation Power: 403
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())))
__________________
[code]Code tags[/code] are essential for python code!

Last edited by b49P23TIvg : August 16th, 2012 at 11:35 AM. Reason: Correction: change index error to key error.

Reply With Quote
  #3  
Old August 16th, 2012, 12:25 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,458 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 4 Days 6 h 26 m 43 sec
Reputation Power: 403
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)]))

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Search the list of objects

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap