Python中与Javascript的reduce()、map()和filter()等价的函数是什么?

43

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)

谢谢大家!


2
reducemapfilter:P,除非您使用python3,在这种情况下它是functools.reduce。请参见此处:https://docs.python.org/2/library/functions.html - NightShadeQueen
我认为它们使用相同的命名方式,就像内置函数一样。 - Iron Fist
你最后的例子不是Array.prototype.map的惯用/正确用法;你应该使用Array.prototype.forEach;[].forEach.call - royhowie
3
这里有一个重要的警告:现在更倾向于使用列表推导式和生成器而不是mapfilter。因此,以下代码似乎更受欢迎:[mutate(x) for x in list if x > 10] - David Ehrmann
4个回答

71

它们都很相似,在Python中通常将lambda函数作为参数传递给这些函数。

Reduce:

 >>> 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]

文档


这差不多是我要找的,但是在lambda内部包含一个函数是否可能? - Henry Lee
1
是的,它就是。例如:doublelength = lambda x: len(x)*2 - user3636636

5
值得注意的是,上面已经从表面上回答了这个问题,并接受了答案,但正如@David Ehrmann在问题评论中提到的那样,最好使用综合来代替mapfilter
为什么呢?如布雷特·斯拉特金在《Effective Python, 2nd Edition》第108页所述:“除非您正在应用单参数函数,否则对于简单情况,列表综合也比map内置函数更清晰。映射需要创建一个用于计算的lambda函数,这在视觉上会有噪音。” 我会补充说明,对于filter同样适用。
例如,假设我想对一个列表进行映射和过滤,以返回列表项的平方,但仅限于偶数项(这是书中的示例)。
使用接受答案的方法使用lambda:
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]

使用解析式:

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

所以,与其他人一样,我建议使用推导式而不是mapfilter。这个问题进一步探讨了这一点。
reduce而言,functools.reduce似乎仍然是正确的选择。

3

0

第一点是:

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


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接