[英]What are Python's equivalent of Javascript's reduce(), map(), and 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)
谢谢大家!
它们都很相似,Lamdba函数经常作为参数传递给python中的这些函数。
降低:
>>> 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 在问题的评论中提到的那样,最好使用理解而不是map
和filter
。
这是为什么? 正如 Brett Slatkin pg 在“Effective Python, 2nd Edition”中所述。 108,“除非你应用单一参数 function,对于简单的情况,列表理解也比map
内置的 function 更清晰map
需要创建一个lambda
88340984068 的计算,视觉上有噪音,88340984068。” 我会为filter
添加同样的内容。
例如,假设我想要 map 并过滤一个列表以返回列表中项目的平方,但只有偶数(这是书中的一个例子)。
使用接受的答案的使用 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]
因此,与其他人一起,我建议使用理解而不是map
和filter
。 这个问题进一步深入。
就reduce
而言, functools.reduce
似乎仍然是正确的选择。
reduce(function, iterable[, initializer])
filter(function, iterable)
map(function, iterable, ...)
首先是:
from functools import *
def wordParts (currentPart, lastPart):
return currentPart+lastPart;
word = ['Che', 'mis', 'try']
print(reduce(wordParts, word))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.