| Store | Cart

list-comprehension and map question (simple)

From: Brian van den Broek <bva...@po-box.mcgill.ca>
Sun, 27 Mar 2005 13:18:02 -0500
Charles Hartman said unto the world upon 2005-03-27 09:51:
> I understand this toy example:> > lines = "this is a group\nof lines of\nwords"> def getlength(w): return len(w)> s = map(getlength, [word for ln in lines.split() for word in  > ln.splitlines()])> > (now s is [4, 2, 1, 5, 2, 5, 2, 5])> > My question is whether there's any compact way to combine function  > calls, like this (which doesn't work):> > lines = "this is a group\nof lines of\nwords"> def getlength(w): return len(w)> def timestwo(x): return x * 2> s = map(timestwo(getlength), [word for ln in lines.split() for word in  > ln.splitlines()])> > (Under the WingIDE I get this traceback:> "/Applications/WingIDE-Professional-2.0.2/WingIDE.app/Contents/MacOS/ > src/debug/server/_sandbox.py", line 1, in ?>     # Used internally for debug sandbox under external interpreter>   File  > "/Applications/WingIDE-Professional-2.0.2/WingIDE.app/Contents/MacOS/ > src/debug/server/_sandbox.py", line 1, in addone>     # Used internally for debug sandbox under external interpreter> TypeError: unsupported operand type(s) for +: 'function' and 'int'> )> > I hope the question is clear enough. I have a feeling I'm ignoring a  > simple technique . . .> > Charles Hartman> 

Hi Charles,

perhaps I'm distracted by the `toy' nature of the examples, but maybe 
this will help:

 >>> lines = "this is a group\nof lines of\nwords">>> [len(x) for x in lines.split()]
[4, 2, 1, 5, 2, 5, 2, 5]
 >>> [len(x)*2 for x in lines.split()]
[8, 4, 2, 10, 4, 10, 4, 10]
 >>> def some_arbitrary_function(y):
... 	return ( (y * 42) - 19 ) % 12
...
 >>> [some_arbitrary_function(len(x)) for x in lines.split()]
[5, 5, 11, 11, 5, 11, 5, 11]
 >>>


I could be missing some edge cases, but it seems to me that if you 
have list comps you don't really need map, filter, and the like. The 
map portion can be done by nested function applications in the list 
comp itself.

Best,

Brian vdB

Recent Messages in this Thread
Charles Hartman Mar 27, 2005 02:51 pm
Nicolas Évrard Mar 27, 2005 03:19 pm
Brian van den Broek Mar 27, 2005 06:18 pm
Charles Hartman Mar 27, 2005 06:35 pm
Brian van den Broek Mar 27, 2005 07:12 pm
Brian van den Broek Mar 27, 2005 07:41 pm
Cameron Laird Mar 30, 2005 07:08 pm
runsun pan Mar 28, 2005 02:51 pm
Robert Kern Mar 28, 2005 03:04 pm
runsun pan Mar 30, 2005 04:32 pm
Messages in this thread