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

tktrz96b  于 2022-11-20  发布在  Java
关注(0)|答案(4)|浏览(117)

下面是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)

谢谢大家!

bqjvbblv

bqjvbblv1#

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

Map:

>>> list(map((lambda x: x **2), [1,2,3,4]))
[1,4,9,16]

Docs

cngwdvgl

cngwdvgl2#

值得注意的是,这个问题已经用上面的公认答案在表面上得到了回答,但是正如@大卫Ehrmann在问题的一条评论中提到的,最好使用理解,而不是mapfilter
为什么会这样呢?正如Brett Slatkin在“Effective Python,2nd Edition”第108页中所述,“除非你应用的是单参数函数,否则列表解析对于简单的情况也比map内置函数更清晰。map需要创建一个lambda函数来进行计算,这在视觉上是嘈杂的。”我想对filter也做同样的补充。
例如,假设我想Map和过滤一个列表,以返回列表中项目的平方,但只返回偶数(这是书中的一个例子)。
使用已接受答案的使用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似乎仍然是合适的选择。

x8diyxa7

x8diyxa73#

reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

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

flmtquvp

flmtquvp4#

首先是:

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

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

相关问题