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

Hen*_*Lee 11 javascript python

什么是Python相当于以下(Javascript):

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

word = ['Che', 'mis', 'try'];
console.log(word.reduce(wordParts))
Run Code Online (Sandbox Code Playgroud)

还有这个:

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)
Run Code Online (Sandbox Code Playgroud)

最后,这个:

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

var greet = names.map(greeting)
Run Code Online (Sandbox Code Playgroud)

谢谢大家!

use*_*636 22

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

降低:

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

过滤:

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

地图:

>>> list(map((lambda x: x **2), [1,2,3,4]))
[1,4,9,16]
Run Code Online (Sandbox Code Playgroud)

文件


jdi*_*zle 7

值得注意的是,这个问题已经在上面用公认的答案从表面上得到了回答,但正如 @David Ehrmann 在问题的评论中提到的,最好使用推导式而不是mapand filter

这是为什么?正如 Brett Slatkin 所著的《Effective Python,第二版》第 10 页所述。108,“除非您应用单参数函数,否则map对于简单情况,列表推导式也比内置函数更清晰。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]
Run Code Online (Sandbox Code Playgroud)

使用理解式:

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

因此,与其他人一起,我建议使用推导式而不是mapand filter。这个问题进一步深入探讨。

就目前而言reducefunctools.reduce这似乎仍然是正确的选择。