• python 函数map()、filter()、reduce()


    map()函数    将一个列表进行遍历,对每一个字符串进行处理:

    例如:

     1 num_list = ["","","哈哈","太平洋海工欢唱","六队船厂","六队码头","六队船坞"]
     2 def add_function(x):
     3     return x + 1
     4 def reduce(x):
     5     return x - 1
     6 def binary(x):
     7     return x ** 2
     8 def test(func, x):
     9     new_list = []
    10     for i in x:
    11         new_list.append(func(i))
    12     return new_list
    13 print(list(map(lambda x:str(x)+"叠加",num_list)))
    14 输出
    15 ['我叠加', '是叠加', '哈哈叠加', '太平洋海工欢唱叠加', '六队船厂叠加', '六队码头叠加', '六队船坞叠加']

    进行对可迭代的对象进行单个处理。

    filter()函数   ,对可遍历的对象进行过滤。适合进行字符串处理。

    例如:

     1 num_list = ["","","哈哈","太平洋海工欢唱","六队船厂","六队码头","六队船坞"]
     2 def filter_list(func,array):
     3     res = []
     4     for i in array:
     5         if func(i):
     6             res.append(i)
     7     return res
     8 print(list(filter_list(lambda x:x.startswith("六队"),num_list)))
     9 print(list(filter(lambda x:x.startswith("六队"),num_list)))
    10 输出
    11 ['六队船厂', '六队码头', '六队船坞']
    12 ['六队船厂', '六队码头', '六队船坞']

    该函数可以对字符串进行处理。返回一个列表的对象。

    reduce()  函数, 该函数对整数进行处理。加减乘除都可以。

    例如:

     1 from functools import reduce
     2 a = [1, 2, 3, 100]
     3 lambda x, y: x * y
     4 
     5 
     6 def num(array, func,init = None):
     7     if init == None:
     8         res = array.pop(0)
     9     else:
    10         res = init
    11     for i in array:
    12         res = func(res, i)
    13     return res
    14 print(reduce(lambda x,y:x*y,a,100))
    15 print(num(a, lambda x, y: x * y,100))
    16 输出
    17 60000
    18 60000

    该函数适合对,某个可迭代的对象进行数据的运算。

  • 相关阅读:
    高德地图API之公交路线
    高德地图API之骑行路线
    高德地图API之货车路线
    高德地图API之步行路线
    高德地图API之驾车路线
    高德地图API常用控件的添加与删除(鹰眼、工具条、比例尺)
    高德地图API,地图类型切换(卫星地图)
    高德地图API之缩放比例尺控件+3D转换
    Laravel 虚拟开发环境 Homestead 密码
    优化mysql
  • 原文地址:https://www.cnblogs.com/ch2020/p/12343370.html
Copyright © 2020-2023  润新知