python3中几个比较重要的内置函数
filter(function, sequence)
函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的filter object
过滤器对象,本质为迭代器对象。
该函数接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中
list1 = ["a","b","c","d"]
def fun(s):
if s != "a":
return s
ret = filter(fun,list1)
print(ret)
print(list(ret))
结果:
C:\Users\AppData\Local\Programs\Python\Python36\python.exe C:/Users/Desktop/study/login/q.py
<filter object at 0x000001B5F28ABAC8>
['b', 'c', 'd']
Process finished with exit code 0
map(function,sequence)
会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的map object
映射对象,本质为迭代器对象
list1 = ["a","b","c","d"]
def fun(s):
return s+"+yes"
ret1 = map(fun,list1)
print(ret1)
print(list(ret1))
结果:
C:\Users\AppData\Local\Programs\Python\Python36\python.exe C:/Users/Desktop/study/login/q.py
<map object at 0x00000258D41EBAC8>
['a+yes', 'b+yes', 'c+yes', 'd+yes']
Process finished with exit code 0
reduce(function,sequence,starting_value)
函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果结果就是一个值。
from functools import reduce
def add_num(x,y):
return x+y
print(reduce(add_num,range(1,10)))#1+2+3+...+9
结果:
C:\Users\AppData\Local\Programs\Python\Python36\python.exe C:/Users/Desktop/study/login/q.py
45
Process finished with exit code 0
lambda
匿名函数操作
from functools import reduce
print(reduce(lambda a,b : a+b , range(1,4)))#阶乘 1 * 2 * 3
结果:
C:\Users\AppData\Local\Programs\Python\Python36\python.exe C:/Users/Desktop/study/login/q.py
6
Process finished with exit code 0