How to use filter, map, and reduce in Python 3

前端 未结 7 1708
夕颜
夕颜 2020-11-22 08:27

filter, map, and reduce work perfectly in Python 2. Here is an example:

>>> def f(x):
        return x % 2 !=         


        
7条回答
  •  旧时难觅i
    2020-11-22 09:17

    Here are the examples of Filter, map and reduce functions.

    numbers = [10,11,12,22,34,43,54,34,67,87,88,98,99,87,44,66]

    //Filter

    oddNumbers = list(filter(lambda x: x%2 != 0, numbers))

    print(oddNumbers)

    //Map

    multiplyOf2 = list(map(lambda x: x*2, numbers))

    print(multiplyOf2)

    //Reduce

    The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:

    from functools import reduce

    sumOfNumbers = reduce(lambda x,y: x+y, numbers)

    print(sumOfNumbers)

提交回复
热议问题