Popular recipes by Michael Hoffman http://code.activestate.com/recipes/users/1453261/2003-10-31T08:03:07-08:00ActiveState Code Recipesimapmethod and friends (Python)
2003-10-31T08:03:07-08:00Michael Hoffmanhttp://code.activestate.com/recipes/users/1453261/http://code.activestate.com/recipes/231504-imapmethod-and-friends/
<p style="color: grey">
Python
recipe 231504
by <a href="/recipes/users/1453261/">Michael Hoffman</a>
(<a href="/recipes/tags/shortcuts/">shortcuts</a>).
</p>
<p>Ever been frustrated at having to separately read data and then do minor processing by calling methods on the data? Find yourself writing lambda functions or short generators to do intermediate processing between iterators? If so, you can simplify your programming life by using imapmethod instead. Imapmethod calls a named method on each item it iterates through. For example, you can replace [x.rstrip() for x in iterable], which inefficiently generates the whole list at once before processing begins, or the more efficient imap(lambda x: x.rstrip(), iterable) with imapmethod("rstrip", iterable) or even the provided irstrip(iterable).</p>
<p>This recipe also illustrates some more brain-twisting uses of itertools.</p>