什么是Python相当于Javascript的reduce(),map()和filter()?

时间:2015-06-30 00:49:17

标签: javascript python

Python的等价物如下(Javascript):

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

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

和此:

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)

最后,这个:

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

var greet = names.map(greeting)

全部谢谢!

3 个答案:

答案 0 :(得分:17)

它们都很相似,Lamdba函数经常作为参数传递给python中的这些函数。

减少:

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

过滤器:

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

地图:

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

Docs

答案 1 :(得分:3)

reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

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

答案 2 :(得分:0)

第一个是:

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


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