Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么是Python';s相当于Javascript';s reduce()、map()和filter()?_Javascript_Python - Fatal编程技术网

什么是Python';s相当于Javascript';s reduce()、map()和filter()?

什么是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 =

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