Python vs. R: apply a function to each element in a vector

I want to apply a function ( len ) to every element in a vector. In R, I can do this with sapply(cities,char) . Is there such an alternative in Python WITHOUT writing a loop?

+5
source share
3 answers

Syntax map(function, list) .

Example:

 map(len, [ [ 1,2,3], [4,5,6] ]) 

Output:

 [ 3, 3 ] 
+4
source

R sapply() can be replaced by a list comprehension, but a fairly fair list comprehension does not allow you to strictly avoid loop writing .

In addition to map() you should take a look at Pandas , which provides Python alternatives to several functions 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 leads to a new list with square imput values:

 [1, 4, 9, 16, 25] 

Here I passed the vector to the pd.Series(vector) series constructor and applied the anonymous apply(lambda x: x**2) function apply(lambda x: x**2) . The output is a series of pandas, which can be converted back to a list if tolist() is required. The pandas series has many features and is ideal for many data management and analysis tasks.

+2
source

You can use a function map that gets a function to apply to iterable. Map documentation: here

For example, you can pass an anonymous function (using lambda) to apply a list to each element as follows:

 >>> map(lambda x: x[1]*2 + 3, [[1,2,3], [1,4]]) [7, 11] 
0
source

Source: https://habr.com/ru/post/1261349/


All Articles