We know that
list(map(f,[1,2],[3,4],[6,7]))
is equivalent to
[f(1,3,6),f(2,4,7)]
I want to know if there is built-in function tolist that is equivalent to [], so that
tolist(a,b,c,d)
is equivalent to [a,b,c,d].
I think such a function is useful in functional programming. Because many functions take list parameter instead of sequence.
Of course, a simple custom way is lambda *x:list(x), but I always feels it is syntactically cumbersome, especially use it in functional programming style like
map(lambda *x:list(x),[1,2],[3,4],[6,7])
So my question is that if there is no such built-in tolist, whether we could build it on the fly more elegantly using FP packages like toolz?
PS: What I actually want to achieve is threaded version of add (I know numpy, but I don't want to use it at the moment)
from toolz.curried import *
import operator as op
def addwise(*args):
return list(map(compose(reduce(op.add),lambda *x:list(x)),*args))
then
addwise([1,2],[3,4],[6,7])
will gives
[10, 13]
If
it is a good sign that
lambdaexpression is not a right fit. You don't want to repeat yourself every time you want to apply this pattern.Sadly we are far from Clojure conciseness:
but we can still express it in a fairly Pythonic and elegant way:
which can be used as:
or even better
although in this case
map, can be combined withzip: