list-comprehension and map question (simple)

Brian van den Broek bvande at po-box.mcgill.ca
Sun Mar 27 13:18:02 EST 2005


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



More information about the Python-list mailing list