Iterating across a filtered list
Arnaud Delobelle
arnodel at googlemail.com
Tue Mar 13 15:21:54 EDT 2007
On Mar 13, 6:04 pm, "Drew" <olso... at gmail.com> wrote:
> All -
Hi!
[snip]
> http://pastie.caboo.se/46647
There is no need for such a convoluted list comprehension as you
iterate over it immediately! It is clearer to put the filtering logic
in the for loop. Moreover you recalculate the regexp for each element
of the list. Instead I would do something like this:
def find(search_str, flags=re.IGNORECASE):
print "Contact(s) found:"
search = re.compile(search_str, flags).search
for name, contact in self.contacts.items():
if search(name):
print contact
print
Although I would rather have one function that returns the list of all
found contacts:
def find(search_str, flags=re.IGNORECASE):
search = re.compile(search_str, flags).search
for name, contact in self.contacts.items():
if search(name):
yield contact
And then another one that prints it.
> 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}
And that's why you're right to learn Python ;)
HTH
--
Arnaud
More information about the Python-list
mailing list