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]
You can convert a set into the list in a defined order using the sorted() function.
Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order.
list() function. The list() function takes an iterable construct and turns it into a list.
To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
If
function is useful (....) Because many functions take list parameter
it is a good sign that lambda
expression 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:
user=> (map + [1 2] [3 4] [6 7])
(10 13)
but we can still express it in a fairly Pythonic and elegant way:
def apply(f):
def _(*args):
return f(args)
return _
which can be used as:
from toolz.curried import reduce
map(apply(reduce(op.add)), [1,2], [3,4], [6,7])
or even better
map(apply(sum), [1,2], [3,4], [6,7])
although in this case map
, can be combined with zip
:
map(sum, zip([1, 2], [3, 4], [6, 7])))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With