Skip to main content

Command Palette

Search for a command to run...

Python Python中的高级函数(魔法函数)

Published
1 min read
Python Python中的高级函数(魔法函数)

Python中的高级函数(魔法函数)

  • filter(内置函数)
  • map(内置函数)
  • reduce(曾经是内置函数)

filter

功能
  • 对循环根据过滤条件进行过滤
用法
  • filter(func, list)
参数介绍
  • func: 对list每个item进行条件过滤的定义
  • list : 需要过滤的列表
举例
  • res = filter(lambda x:x > 1, [0,1,2])
返回值
  • <filter at 0x4f3af70> -> [1,2]

map

功能
  • 对列表中的每个成员是否满足条件返回对应的TrueFalse
用法
  • map(func, list)
参数介绍
  • func: 对List每个item进行条件满足的判断
  • list: 需要过滤的列表
举例
  • res = map(lambda x:x > 1, [0,1,2])
返回值
  • <map at 0x4f3af70> -> [False, False, True]

reduce

功能
  • 对循环前后两个数据进行累加
用法
  • reduce(func, list)
参数介绍
  • func : 对 数据累加的函数
  • list : 需要处理的列表
举例
  • res = reduce(lambda x,y: x + y, [0,1,2])
返回值
  • 数字 -> 3
reduce的导入
  • from functools import reduce

代码

# coding:utf-8

from functools import reduce

frunts = ['apple', 'banana', 'orange']

result = filter(lambda x: 'e' in x, frunts)
print(list(result))
print(frunts)


def filter_func(item):
    if 'e' in item:
        return True


print('--------')
filter_result = filter(filter_func, frunts)
print(list(filter_result))

map_result = map(filter_func, frunts)  # > all
print(list(map_result))


reduce_result = reduce(lambda x, y: x + y, [2, 1, 2, 100])
print(reduce_result)

reduce_result_str = reduce(lambda x, y: x + y, frunts)
print(reduce_result_str)
1 views

More from this blog

MySQL | 表的内连接

数据操作语言:表连接查询(一) 从多张表中提取数据 从多张表提取数据,必须指定关联的条件。如果不定义关联条件就会出现无条件连接,两张表的数据会交叉连接,产生 笛卡尔积。 规定了连接条件的表连接语句,就不会出现笛卡尔积。 # 查询每名员工的部门信息 SELECT e.empno,e.ename,d.dname FROM t_emp e JOIN t_dept d ON e.deptno=d.deptno; 表连接的分类 表连接分为两种:内连接 和 外连接 内连接是结果集中只保留符合...

May 16, 20221 min read13
MySQL | 表的内连接

MySQL | 分组查询的应用

数据操作语言:分组查询 为什么要分组? 默认情况下汇总函数是对全表范围内的数据做统计 GROUP BY 子句的作用是通过一定的规则将一个数据集划分成若干个小的区域,然后针对每个小区域分别进行数据汇总处理 SELECT deptno,AVG(sal) FROM t_emp GROUP BY deptno; SELECT deptno,ROUND(AVG(sal)) FROM t_emp GROUP BY deptno; -- ROUND 取整 逐级分组 数据库支持多列分组条件,执行的时候...

Apr 27, 20221 min read10
MySQL | 分组查询的应用

MySQL | 聚合函数的使用

数据操作语言:聚合函数 什么是聚合函数 聚合函数在数据的查询分析中,应用十分广泛。聚合函数可以对 数据求和、求 最大值 和 最小值 、求 平均值 等等。 求公司员工的评价月收入是多少? SELECT AVG(sal+IFNULL(comm,0)) FROM t_emp; SELECT AVG(sal+IFNULL(comm,0)) AS avg FROM t_emp; SUM 函数 SUM 函数用于求和,只能用户数字类型,字符类型的统计结果为 0 ,日期类型统计结果是毫秒数相加 SE...

Apr 26, 20221 min read8
MySQL | 聚合函数的使用
U

Untitled Publication

173 posts