其他分享
首页 > 其他分享> > 003_map_filter_reduce

003_map_filter_reduce

作者:互联网

 

"""
目录: 
    一 map
    二 filter
    三 reduce
"""

 

一 map

def square(x):
    return x ** 2


if __name__ == '__main__':
    list_1 = [1, 2, 3, 4, 5]
    map_object = map(square, list_1)
    print(map_object)       # <map object at 0x0000022C060F6FD0>
    print(list(map_object)) # [1, 4, 9, 16, 25]

    map_object = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
    print(list(map_object)) # [1, 4, 9, 16, 25]

 


二 filter

def is_odd(n):
    return n % 2 == 1

if __name__ == '__main__':
    my_list = [i for i in range(10)]

    temlist = filter(is_odd, my_list)
    print(list(temlist))    # [1, 3, 5, 7, 9]

 


三 reduce

from functools import reduce


def mult(x, y):
    return x * y

if __name__ == '__main__':
    sum_1 = reduce(mult, [1, 2, 3, 4, 5])
    sum_2 = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
    print(sum_1)    # 120
    print(sum_2)    # 15

 

标签:__,map,reduce,object,list,003,print
来源: https://www.cnblogs.com/huafan/p/16449263.html