filter function question - list processing in Python

Greg Ewing greg.ewing at compaq.com
Wed Nov 24 09:33:03 EST 1999


lobozc at my-deja.com wrote:
> 
> How should I pass additional parameter in 'filter'? 'map' has them,
> filter doesn't - why? Say I have a list ['xxx.py','xxx.pyc'] and I want
> to have a function isExtension(x,'.py')
> [No, I'm not interested in using lambda here in general].

Why not? That's the shortest way to do it:

   def filterExt(items, ext):
      return filter(lambda x, ext=ext: isExtension(x,ext), items)

However, a more Pythonic way of writing that is

   def filterExt(items, ext):
      result = []
      for x in items:
         if isExtension(x, ext):
            result.append(x)
      return result

which is longer-winded but clearer. If you want something which
is both short-winded and clear, you might like to try my List
Comprehension syntax extension, which allows you to write

   def filterExt(items, ext): # NOT STANDARD PYTHON
      return [x for x in items if isExtension(x, ext)]

The List Comprehensions patch is available from my web page:
http://www.cosc.canterbury.ac.nz/~greg

Greg








 - which I can call with various
> extensions to filter the list in variuos ways - how am I supposed to do
> that? [No, I'm not interested in using lambda here in general].
> 
> In general, I note that Python has some standard functions operating on
> lists but they are curiously limited. It is a pity, since these are the
> functions which reduce line count significantly - as well as make
> programming safer. I wonder what are the chances of repeating with
> lists what Python did with regular expressions - copying the
> functionality from a well tested and popular product?
> 
> Mathematica has a set of list processing functions. As one can expect
> from an essentially functional language and a product where most
> operations are done by list processing - for the last 10 years - this
> set is well thought out, complete and very, very useful.
> 
> [For description see
> http://documents.wolfram.com/v4/frames/frames.html, press button 'built-
> in functions', on the leftmost panel 'programming', to the right of it
> press 'functional programming' - eventually look for functions like
> Map, Fold, Apply etc.].
> 
> Sent via Deja.com http://www.deja.com/
> Before you buy.




More information about the Python-list mailing list