What are Python's equivalent of Javascript's reduce(), map(), and filter()?

前端 未结 3 695
轮回少年
轮回少年 2021-01-31 10:27

What are Python\'s equivalent of the following (Javascript):

function wordParts (currentPart, lastPart) {
    return currentPart+lastPart;
}

word = [\'Che\', \'         


        
相关标签:
3条回答
  • 2021-01-31 10:59

    They are all similar, Lamdba functions are often passed as a parameter to these functions in python.

    Reduce:

     >>> from functools import reduce
     >>> reduce( (lambda x, y: x + y), [1, 2, 3, 4]
     10
    

    Filter:

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

    0 讨论(0)
  • 2021-01-31 11:06

    The first is:

    from functools import *
    def wordParts (currentPart, lastPart):
        return currentPart+lastPart;
    
    
    word = ['Che', 'mis', 'try']
    print(reduce(wordParts, word))
    
    0 讨论(0)
  • 2021-01-31 11:14
    reduce(function, iterable[, initializer])
    
    filter(function, iterable)
    
    map(function, iterable, ...)
    

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

    0 讨论(0)
提交回复
热议问题