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

前端 未结 7 1706
夕颜
夕颜 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条回答
  •  一生所求
    2020-11-22 09:16

    from functools import reduce
    
    def f(x):
        return x % 2 != 0 and x % 3 != 0
    
    print(*filter(f, range(2, 25)))
    #[5, 7, 11, 13, 17, 19, 23]
    
    def cube(x):
        return x**3
    print(*map(cube, range(1, 11)))
    #[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
    
    def add(x,y):
        return x+y
    
    reduce(add, range(1, 11))
    #55
    

    It works as is. To get the output of map use * or list

提交回复
热议问题