I want to apply a function (len
) over each element in a vector. In R I can easily do this with sapply(cities,char)
. Is there an alternative like this in Python WITHOUT writing a loop?
4 Answers
The syntax is map(function, list)
.
Example:
map(len, [ [ 1,2,3], [4,5,6] ])
Output:
[ 3, 3 ]
The R sapply()
could be replaced with a list comprehension, but fair enough a list comprehension doesn't strictly avoid the writing of a loop.
In addition to map()
you should take a look at Pandas, which provides Python alternatives to several of the functionality that people use in R.
import pandas as pd
vector = [1,2,3,4,5]
square_vector = pd.Series(vector).apply(lambda x: x**2)
print square_vector.tolist()
The above code results in a new list with the square values of the imput:
[1, 4, 9, 16, 25]
Here, I passed the vector to a series constructor pd.Series(vector)
and apply an anonymus function apply(lambda x: x**2)
. The output is a pandas series which can be converted back to a list if desired tolist()
. Pandas series have a lot of functionalities and are ideal for many data manipulation and analysis tasks.
You can use function map that receives a function to apply to an iterable. Documentation to map map: here
For example, you cans pass an anonymus function (using lambda) to apply to each element to the list by this way:
>>> map(lambda x: x[1]*2 + 3, [[1,2,3], [1,4]])
[7, 11]
Consider this:
cities = ['new york', 'tokyo', 'paris']
sapply_equivalent = [len(city) for city in cities]
Then sapply_equivalent
returns [8, 5, 5]
[len(el) for el in vector]
. It's more Pythonic thanmap
.sapply
is a loop!