Iterating across a filtered list

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 13 16:59:32 EDT 2007


En Tue, 13 Mar 2007 15:04:50 -0300, Drew <olsonas at gmail.com> escribió:

> I'm currently writing a toy program as I learn python that acts as a
> simple address book. I've run across a situation in my search function
> where I want to iterate across a filtered list. My code is working
> just fine, but I'm wondering if this is the most "elegant" way to do
> this. Essentially, I'm searching the dict self.contacts for a key that
> matches the pattern entered by the user. If so, I print the value
> associated with that key. A pastie to the method is below, any help/
> advice is appreciated:
>
> http://pastie.caboo.se/46647
>
> Side note: I'm learning python after ruby experience. In ruby I would
> do something like:
>
> contacts.find_all{|name,contact| name =~ /search/}.each{|name,contact|
> puts contact}
>

Just a few changes:

def find(self, search):
     search_re = re.compile(search, re.IGNORECASE)
     for result in [self.contacts[name] for name in self.contacts if  
search_re.match(name)]:
         print result

- you can iterate directly over a dictionary keys using: for key in dict
- you can compile a regexp to re-use it in all loops; using re.IGNORECASE,  
you don't need to explicitely convert all to lowercase before comparing
- if all you want to do is to print the results, you can even avoid the  
for loop:

     print '\n'.join('%s' % self.contacts[name] for name in self.contacts  
if search_re.match(name))

-- 
Gabriel Genellina




More information about the Python-list mailing list