文章目录

  • 高阶函数
  • map函数
  • 练习
  • filter函数
  • 练习
  • sorted函数
  • 练习
  • reduce函数
  • 综合练习


高阶函数

定义:把函数作为参数传入,这样的函数称为高阶函数

示例:

def add(x, y, f):
    return f(x)+f(y)
print(add(-5,6,abs))
# 11

map函数

map()是 Python 内置的高阶函数,它接收一个函数function 和一个可迭代对象,并通过把函数 function 依次作用在可迭代对象的每个元素上,得到一个新的 list 并返回。

# map
# 求取列表中每个元素的平方值
lst = [1, 2, 3, 4, 5]
lst2 = [3, 6, 7]
def func(item):
    return item * item
result = map(func, lst)
print(result)
#<map object at 0x02D4A5B0>
print(list(result)) #map对象是可迭代对象,可直接用list转换
#[1, 4, 9, 16, 25]

result2 = map(lambda x:x**2, lst) #函数比较简单,使用匿名函数
print(list(result2))
#[1, 4, 9, 16, 25]

# map中函数传递两个参数,后面就要传递两个可迭代对象
print(list(map(lambda x,y:x+y, lst, lst2)))
#[4, 8, 10]

练习

# 有列表[1,2,3,4,5] ,将所有元素转换成str:['1','2','3','4','5']
lst1 = [1,2,3,4,5]
print(list(map(lambda x:str(x) , lst1)))
print(list(map(str, lst1)))
#['1', '2', '3', '4', '5']

# 有列表字符串'span' ,将各字符转换成对应的ascii码的列表[115, 112, 97, 109]
str1 = 'span'
print(list(map(lambda x:ord(x) , str1)))
print(list(map(ord, str1)))
#[115, 112, 97, 110]

# 有列表[-1,-2,0,1,2] ,将各元素转换成绝对值[1, 2, 0, 1,2]
lst2 = [-1,-2,0,1,2]
print(list(map(lambda x:abs(x) , lst2)))
print(list(map(abs, lst2)))
#[1, 2, 0, 1, 2]

# 列表 a = [0.23432, 2.3232 , 6.24322, 8.23432]保留两位小数
a = [0.23432, 2.3232 , 6.24322, 8.23432]
print(list(map(lambda x:round(x,2) , a)))
#[0.23, 2.32, 6.24, 8.23]

# 将列表中的数转化为百分比输出,保留两位小数 --23.43%
a2 = [0.23432, 2.3232 , 6.24322, 8.23432]
print(list(map(lambda x:f'{round(x*100,2)}%' , a2)))
#['23.43%', '232.32%', '624.32%', '823.43%']

filter函数

filter()接收一个函数function 和一个可迭代对象,这个function 的作用是对可迭代对象的每个元素进行判断,返回True或False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新可迭代对象。

# filter
# 过滤
# 取出10以内的奇数
result = filter(lambda x : x % 2, range(10))
#x % 2 为1时返回值为真,保留--》奇数,为假的去掉
print(list(result))
#[1, 3, 5, 7, 9]

练习

# 1-200以内开平方是整数的数
import math
result = filter(lambda x:math.sqrt(x).is_integer() ,range(1,200))
print(list(result))
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196]

# 过滤出100-999以内的水仙花数
# 153 = 1的立方 + 5的立方 + 3的立方
# def func1(x):
#     if x == ((x%10)**3 + (x%100//10)**3 + (x//100)**3):
#         return x
result = filter(lambda x:x == ((x%10)**3 + (x%100//10)**3 + (x//100)**3),range(100,1000))
print(list(result))
#[153, 370, 371, 407]

# 把一个序列中的空字符串删掉 , ['A','', 'B', None, 'C' ,' ', 'a', 1, 0]
# ['A', 'B','C', 'a',1]
lst = ['A','', 'B', None, 'C' ,' ', 'a', 1, 0]
result = filter(lambda x:x and str(x).strip(),lst)
print(list(result))
#['A', 'B', 'C', 'a', 1]

sorted函数

print(sorted([True,Flase]))===>结果[False,True]

Boolean 的排序会将 False 排在前,True排在后

# sorted 排序
lst = [-6, 3, 2, -9, 7]
# # lst.sort()
# # print(lst)
# lst1 = lst.copy()
# lst1.sort()
# print(lst, lst1)

print(sorted(lst,key=abs))
# [0, True, True, 2]
lst2 = [True, len(lst)>2 ,0,2] #True=1 False=0
print(sorted(lst2))
#[0, True, True, 2]

lst3 = [1, 5, 'a', 7]
print(sorted(lst3)) # 不同类型不能进行排序

# 列表里面包元组的形式排序
# 先按照第一个值进行排序,第一个值都一样就按照第二个值进行排序,依次类推
lst = [(True, True, False),
       (2, 1, 3),
       (2, 2, 4),
       (False, True, 2),
       (False, False, 3)]
print(sorted(lst))
# [(False, False, 3), (False, True, 2), (True, True, False), (2, 1, 3), (2, 2, 4)]

练习

# 1.列表中的值忽略大小写排序
lst = ['bob','Ab','c']
print(sorted(lst,key=lambda x:x.lower()))
print(sorted(lst,key=str.upper))
# ['Ab', 'bob', 'c']
print(str.upper("abc"))
#ABC

# 2.按照字典的value值进行排序
d1 = {'a':3,'b':2,'c':4,'d':1}
print(d1.items())
#dict_items([('a', 3), ('b', 2), ('c', 4), ('d', 1)])
print(dict(sorted(d1.items(),key=lambda x:x[1])))
#{'d': 1, 'b': 2, 'a': 3, 'c': 4}

# 3.cat access.log |grep alibaba|sort|uniq -c|sort -nr|head -10用python实现
line_dict = {}
with open("access.log") as fp:
    for line in fp:
        if 'alibaba' in line:
            #print(line)
            line_dict[line] = line_dict.get(line,0)+1
            # print(line_dict)
result = sorted(line_dict.items(), key = lambda x:x[1],reverse = True)[:10]
print(result)

reduce函数

reduce()函数也接收一个函数function, 和一个可迭代对象。但reduce()传入的函数必须接收两个参数,reduce()对可迭代对象的每个元素反复调用函数function, 并返回最终结果值。

# reduce -- 累计
# 这个函数必须接收两个参数
from functools import reduce
a = [1,2,3,4]
def func1(x,y):
    return x * 10 + y
print(reduce(func1,a))
#1234

综合练习

# lst = ['a', '1', '2bb', '234','','9']
# 使用reduce取出lst的数字 --》 12349
lst = ['a', '1', '2bb', '234','','9']
# digit = []
from functools import reduce
# for i in lst:
#     if i.isdigit():
#         digit.append(i)
# print(digit)
result = filter(lambda x:x.isdigit(),lst)
print(reduce(lambda x,y:x+y,list(result)))
# 12349

# print(sorted([True,Flase]))===>结果[False,True]
# Boolean 的排序会将 False 排在前,True排在后

# 有以下列表: list1=[7,-8,5, 4, 0,-2, -5]
# 正数在前负数在后
# 正数从小到大
# 负数从大到小
list1=[7,-8,5, 4, 0,-2, -5]
result = sorted(list1,key=lambda x:(x<=0,abs(x))) # 先根据正负排大小,0和负数为True,会排在后面,再根据绝对值的大小排序
print(result)
# [4, 5, 7, 0, -2, -5, -8]

# 这是一个字符串排序,排序规则:小写<大写<奇数<偶数
# S = 'asdf234GDSdsf23' #排序:小写-大写-奇数-偶数
# 原理:先比较元组的第一个值,FALSE
S = 'asdf234GDSdsf23'
s2 = "".join(sorted(S, key=lambda x: (x.isdigit(),x.isupper(),x.isdigit() and int(x) % 2 == 0,x)))
# x.isdigit() 数字为True,会排在后面 ==》 字母<数字
# x.isupper() 大写为True,那么大写会在小写后面  ==》 小写<大写
# x.isdigit() and int(x) % 2 == 0 偶数为True,偶数排在后面   ==》 奇数<偶数
print(s2)
# addffssDGS33224