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



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)

谢谢大家!

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

减少:

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

单据

值得注意的是,这个问题已经用公认的答案从表面上回答了,但正如@David Ehrmann在该问题的评论中提到的那样,最好使用综合而不是mapfilter

为什么?如";有效Python,第二版";由Brett Slatkin第108页;除非您应用的是单参数函数,否则对于简单情况,列表理解也比map内置函数更清晰。map需要为计算创建lambda函数,该函数在视觉上是有噪声的"我想为filter添加同样的内容。

例如,假设我想在列表上进行映射和过滤,以返回列表中项目的平方,但只返回偶数(这是书中的一个例子)。

使用公认答案的使用lambdas:的方法

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似乎仍然是合适的选择。

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

最新更新