什么是Python';s相当于Javascript';s reduce()、map()和filter()?
Python与以下内容(Javascript)的等价物是什么: 这是:什么是Python';s相当于Javascript';s reduce()、map()和filter()?,javascript,python,Javascript,Python,Python与以下内容(Javascript)的等价物是什么: 这是: 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 =
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)
谢谢大家
reduce(function, iterable[, initializer])
filter(function, iterable)
map(function, iterable, ...)
它们都很相似,在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]
第一个是:
from functools import *
def wordParts (currentPart, lastPart):
return currentPart+lastPart;
word = ['Che', 'mis', 'try']
print(reduce(wordParts, word))
reduce
、map
和filter
:P除非您使用的是python3,在这种情况下,它是functools。reduce
请参见此处:我认为与内置函数的命名相同。最后一个示例不是数组.prototype.map
的惯用/正确用法;您应该改为使用Array.prototype.forEach
或;[].forEach.call
答案上的巨大警告,这里是:现在列表理解和生成器似乎比map
和filter
更受青睐。所以它看起来像是[如果x>10,则在列表中对x进行变异(x)]
这就是我要寻找的,但是有可能在lambda中包含一个函数吗?是的。例如,双长度=λx:len(x)*2
>>> list(map((lambda x: x **2), [1,2,3,4]))
[1,4,9,16]
from functools import *
def wordParts (currentPart, lastPart):
return currentPart+lastPart;
word = ['Che', 'mis', 'try']
print(reduce(wordParts, word))