[Tutor] filtering within a function.
Michael P. Reilly
arcege@shore.net
Mon, 12 Mar 2001 13:36:35 -0500 (EST)
> Revising cipher.py...
> http://www.lowerstandard.com/python/cipher.py
> to eliminate import of string, and discovered
> that the unstray function is bugged something
> awful (guess it usually gets the right input;
> this has gone unnoticed for a couple months).
>
> Given:
> >>> foo = list('UPPERlowerUPPER12345')
>
> This appears to work:
>
> >>> uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
> >>> def f(x): return x in uppercase
> ...
> >>> filter(f, foo)
> ['U', 'P', 'P', 'E', 'R', 'U', 'P', 'P', 'E', 'R']
>
> Can't seem to make it work inside the function.
That is probably because unstray relies on side-effects of the function
parameter, which is usually a bad design choice (but not always). Here
the problem is that unstray returns nothing and modifies listinput.
What you can do is overwrite the list's elements.
How about:
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def unstray(listinput, f=lambda x: x in uppercase):
l = filter(f, listinput)
# replace the contents of listinput with the result of the filtering
listinput[:] = l
But then, maybe I'm missing the point. :)
-Michael
--
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager | Email: arcege@shore.net |
| Salem, Mass. USA 01970 | |
------------------------------------------------------------------------