Python与Javascript的reduce()、map()和filter()等价吗?

2024-06-10 01:27:59 发布

您现在位置: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)

谢谢大家!


Tags: namelogcitynewreturnvarfunctionconsole
3条回答
reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

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

首先是:

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


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

它们都是相似的,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

相关问题 更多 >