What is the Python equivalent of Javascript reduce (), map () and filter ()?

What is the Python equivalent of the following (Javascript):

function wordParts (currentPart, lastPart) {
    return currentPart+lastPart;
}

word = ['Che', 'mis', 'try'];
console.log(word.reduce(wordParts))

      

and this:

var places = [
    {name: 'New York City', state: 'New York'},
    {name: 'Oklahoma City', state: 'Oklahoma'},
    {name: 'Albany', state: 'New York'},
    {name: 'Long Island', state: 'New York'},
]

var newYork = places.filter(function(x) { return x.state === 'New York'})
console.log(newYork)

      

Finally, this:

function greeting(name) {
    console.log('Hello ' + name + '. How are you today?');
}
names = ['Abby', 'Cabby', 'Babby', 'Mabby'];

var greet = names.map(greeting)

      

Thanks everyone!

+3


source to share


3 answers


They are all similar, Lamdba functions are often passed as parameters to these functions in python.

Reduce:

 >>> from functools import reduce
 >>> reduce( (lambda x, y: x + y), [1, 2, 3, 4]
 10

      

Filter:



>>> list( filter((lambda x: x < 0), range(-10,5)))
[-10, -9, -8, -7, - 6, -5, -4, -3, -2, -1]

      

Map:

>>> list(map((lambda x: x **2), [1,2,3,4]))
[1,4,9,16]

      

Docs

+9


source


reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

      



https://docs.python.org/2/library/functions.html

+3


source


First:

from functools import *
def wordParts (currentPart, lastPart):
    return currentPart+lastPart;


word = ['Che', 'mis', 'try']
print(reduce(wordParts, word))

      

0


source







All Articles