This is quite n00bish, but I’m trying to learn/understand functional programming in python. The following code:
foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars)
produces:
1.0 1 2.0 2 3.0 3 4.0 None 5.0 None
Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc.
1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3]
Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g.
foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5]
and print:
1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ...
P.S: I know how to do it naively using if, loops and/or generators, but I’d like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest?
The easiest way would be not to pass
barsthrough the different functions, but to access it directly frommaptest:With your original
maptestfunction you could also use a lambda function inmap: