下面是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)
谢谢大家!
4条答案
按热度按时间bqjvbblv1#
它们都是相似的,在Python中,lamdba函数通常作为参数传递给这些函数。
减少:
筛选器:
Map:
Docs
cngwdvgl2#
值得注意的是,这个问题已经用上面的公认答案在表面上得到了回答,但是正如@大卫Ehrmann在问题的一条评论中提到的,最好使用理解,而不是
map
和filter
。为什么会这样呢?正如Brett Slatkin在“Effective Python,2nd Edition”第108页中所述,“除非你应用的是单参数函数,否则列表解析对于简单的情况也比
map
内置函数更清晰。map
需要创建一个lambda
函数来进行计算,这在视觉上是嘈杂的。”我想对filter
也做同样的补充。例如,假设我想Map和过滤一个列表,以返回列表中项目的平方,但只返回偶数(这是书中的一个例子)。
使用已接受答案的使用lambda的方法:
使用解析:
因此,和其他人沿着,我建议使用解析而不是
map
和filter
。就
reduce
而言,functools.reduce
似乎仍然是合适的选择。x8diyxa73#
https://docs.python.org/2/library/functions.html
flmtquvp4#
首先是: