【问题标题】:What are Python's equivalent of Javascript's reduce(), map(), and filter()?Python 的 Javascript 的 reduce()、map() 和 filter() 等价物是什么?
【发布时间】:2015-06-30 00:49:17
【问题描述】:

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

谢谢大家!

【问题讨论】:

  • reduce, map, 和 filter :P 除非你在 python3 中,在这种情况下它是 functools.reduce 见这里:docs.python.org/2/library/functions.html
  • 我认为是内置函数的相同命名。
  • 你的最后一个例子不是Array.prototype.map的惯用/正确使用;你应该改用Array.prototype.forEach;[].forEach.call
  • 对答案的巨大警告,在这里:列表推导和生成器似乎比mapfilter 更受青睐,这些天。所以它看起来像[mutate(x) for x in list if x > 10]

标签: javascript python


【解决方案1】:

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

Docs

【讨论】:

  • 这就是我正在寻找的东西,但是否可以在 lambda 中包含一个函数?
  • 是的。例如。 doublelength = lambda x: len(x)*2
【解决方案2】:
reduce(function, iterable[, initializer])

filter(function, iterable)

map(function, iterable, ...)

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

【讨论】:

    【解决方案3】:

    第一个是:

    from functools import *
    def wordParts (currentPart, lastPart):
        return currentPart+lastPart;
    
    
    word = ['Che', 'mis', 'try']
    print(reduce(wordParts, word))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 2013-07-01
      • 2011-03-24
      • 1970-01-01
      相关资源
      最近更新 更多