python(内置高阶函数)

1.高阶函数介绍:

  • 一个函数可以作为参数传给另外一个函数,或者一个函数的返回值为另外一个函数(若返回值为该函数本身,则为递归),如果满足其一,则为高阶函数。
  • 常见的高阶函数:map()、sorted()、filter()等也是python内置的函数,也可以自定义高阶函数,其实装饰器也算一种高阶函数。

2.内置高阶函数:

(1)map(function,iterable) 函数

  • function:接收一个函数
  • iterable:接受一个可迭代对象(字符串,元组,列表,字典)
  • 作用:可将迭代对象 __iter1 依次代入这个函数,然后将结果组成一个列表返回
"""
#将列表 a 中的元素全部转换成字符串
a = [1,2,3,4]

b = map(str,a)
print(list(b))
"""

"""
#将下面stu列表中的姓氏进行首字母大写操作
stu = ["ZHAo","qIan","SUN","Li"]
#自定义首字母大写方法
def NameStyle(name):
    return name[0].upper() + name[1:].lower()
#使用map()函数,传入参数为,自定义的函数NameStyle名称,和可迭代对象stu
stu2 = map(NameStyle,stu)
print(list(stu2))
"""

(2)filter(function,iterable) 函数

  • function:接收一个函数
  • iterable:接受一个可迭代对象
  • 作用:将可迭代对象依次传入该函数,通过返回值是 True 或 False 决定去留(过滤或筛选)
"""
#找出列表 strs 中的所有字符串
strs = ["a","b","c",1,2]
def get_str(x):
    if isinstance(x,str):   #判断传入的元素 x 是否是 str 型
        return True
new_strs = filter(get_str,strs)
print(list(new_strs))
"""

"""
#找出列表中http链接
http = ["http://www.baidu.com","apple","http://weibo.cn","中国人"]
def ht(param):
    if param.startswith("http"):
        return True
        
all_http = filter(ht,http)
print(list(all_http))
"""

 (3)sorted(iterable,key,reverse) 函数

  • iterable:可迭代对象
  • key:主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序
  • reverse:排序规则,reverse = True 降序 , reverse = False 升序(默认)
  • 返回值:返回重新排序的列表
"""
#根据成绩排序
grade = [("Tom",75),("Jerry",92),("Apple",66),("Ben",88)]

def get_grade(x):
    return x[1]

print(sorted(grade,key=get_grade))
"""

"""
# 根据字符串长度排序
name = ["Tom","Jerry","Apple","Ben"]

def len_name(x):
    return len(x)

print(sorted(name,key=len_name))
"""

猜你喜欢

转载自www.cnblogs.com/ZhengYing0813/p/12395087.html