简体   繁体   中英

What are Python's equivalent of Javascript's reduce(), map(), and filter()?

What are Python's 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)

lastly, this:

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

var greet = names.map(greeting)

Thanks all!

They are all similar, Lamdba functions are often passed as a parameter 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

It is worth noting that this question has been answered at face value above with the accepted answer, but as @David Ehrmann mentioned in a comment in the question, it is preferred to use comprehensions instead of map and filter .

Why is that? As stated in "Effective Python, 2nd Edition" by Brett Slatkin pg. 108, "Unless you're applying a single-argument function, list comprehensions are also clearer than the map built-in function for simple cases. map requires the creation of a lambda function for the computation, which is visually noisy." I would add the same goes for filter .

eg let's say I want to map and filter over a list to return the square of the items in the list, but only the even ones (this is an example from the book).

Using the accepted answer's method of using lambdas:

arr = [1,2,3,4]
even_squares = list(map(lambda x: x**2, filter(lambda x: x%2 == 0, arr)))
print(even_squares) # [4, 16]

Using comprehensions:

arr = [1,2,3,4]
even_squares = [x**2 for x in arr if x%2 == 0]
print(even_squares) # [4, 16]

So, along with others, I would advise using comprehensions instead of map and filter . This question dives into it even further.

As far as reduce goes, functools.reduce still seems like the proper option.

reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

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

The first is:

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM