zoukankan      html  css  js  c++  java
  • 高阶函数 map,reduce, filter的用法

    1. map 用法

     1 def fun_C(x):
     2     """求平方"""
     3     return x ** 2
     4 
     5 
     6 result = map(fun_C, my_list)
     7 print(list(result))
     8 
     9 my_list1 = ["smith", "edward", "john", "obama", "tom"]
    10 
    11 
    12 def f(d):
    13     """将列表小写首字母转换为大写字母"""
    14     return d[0].upper() + d[1:]
    15 
    16 
    17 result1 = map(f, my_list1)
    18 print(list(result1))

    2. reduce 用法

    对列表中的数字进行累加计算

    需要使用 import functools 模块

     1 # reduce模块头文件
     2 import functools
     3 
     4 my_list = [1, 2, 3, 4, 5, 6]
     5 
     6 def sum(a, b):
     7     return a + b
     8 
     9 ret = functools.reduce(sum, my_list)
    10 print(ret)

    3. filter 用法

    filter() 函数用于过滤序列, 过滤掉不符合条件的元素, 返回一个 filter 对象, 如果要转换为列表, 可以使用 list() 来转换.

     1 my_list = [1, 2, 3, 4, 5, 6]
     2 
     3 
     4 def f(x):
     5     """过滤掉奇数"""
     6     return x % 2 == 0
     7 
     8 
     9 result = filter(f, my_list)
    10 print(list(result))
    11 
    12 my_list1 = ["smith", "Edward", "john", "Obama", "tom"]
    13 
    14 
    15 def d(w):
    16     """过滤掉列表中首字母为大写的单词"""
    17     return w[0].isupper()
    18 
    19 
    20 ret = filter(d, my_list1)
    21 print(list(ret))
  • 相关阅读:
    2019-04-02 cast and covert
    2019-04-01 为什么零售业务流行起来了?
    2019-04-01 银行的零售业务和对公业务
    服务器推送更新
    webpack 大概
    webpack
    react Hooks
    react 表单受控和非受控
    eslint规则
    react系列笔记:第三记-redux-saga
  • 原文地址:https://www.cnblogs.com/SP-0306/p/10905951.html
Copyright © 2011-2022 走看看