【Python | 高阶函数map、filter、sorted、reduce的使用】


前言

环境准备:
Windows10
PyCharm2020.3 x64


高阶函数

  • 把函数作为参数传入,这样的函数称为高阶函数
def add(x,y,f):
    return f(x) + f(y)
add(-5, 6, abs)

1. map函数

  • 映射

  • 求取列表中每个元素的平方值

lst = [1, 2, 3, 4, 5]

def func(item):
    return item * item

result = map(func, lst)
print(result)  # <map object at 0x00000203F8551FA0>
print(list(result))  # [1, 4, 9, 16, 25]
  • 使用匿名函数
result = map(lambda x:x**2, lst)
print(list(result))  # [1, 4, 9, 16, 25]
  • 求和 => 多个可迭代对象
lst = [1, 2, 3, 4, 5]
lst2 = [3, 6, 7]

result = map(lambda x,y:x+y, lst, lst2)
# 以最短的可迭代对象为标准
print(list(result))  # [4, 8, 10]

练习

# 1. 将列表内的数字转换为字符串类型
lst1 = [1, 2, 3, 4, 5]
# result1 = map(lambda i:str(i), lst1)
result1 = map(str, lst1)
print(list(result1))

# 2. 将列表字符串转换成对应的ASCII码 => 列表
lst2 = 'span'
# result2 = map(lambda i:ord(i), lst2)
result2 = map(ord, lst2)
print(list(result2))

# 3. 列表元素转换为绝对值
lst3 = [-1, -2, 0, 1, 2]
# result3 = map(lambda i:abs(i), lst3)
result3 = map(abs, lst3)
print(list(result3))

# 列表a = [0.346574, 2.34534, 6.34523, 8.234534]
# 将列表中的数转化为百分比输出,保留两位小数 -- 34.66%
lst4 = [0.346574, 2.34534, 6.34523, 8.234534]
result4 = map(lambda i:round(i,2), lst4)
print(list(result4))
result5 = map(lambda i:i*100, list(result4))
print(list(result5))

2. filter函数

  • 过滤

  • 取出10以内的奇数

    • x % 2 的结果为0 => 说明是为假 => 去除
      1 => 说明是为真 => 保留
    result = filter(lambda x:x %2, range(10))
    print(list(result))
    
  • 1-200以内开平方是整数的数

    import math
    print(list(filter(lambda x:math.sqrt(x) % 1 == 0, range(1, 201))))
    
  • 过滤出100-999以内的水仙花数

    • 水仙花数:153 = 1的立方 + 5的立方 + 3的立方
    print(list(filter(lambda x:x == (x % 10)**3 + (x //10 % 10)**3 + (x//100)**3, range(100, 1000))))
    
  • 把一个序列中的空字符串删掉,[‘A’, ‘’, ‘B’, None, ‘C’, ’ ', ‘a’, 1, 0]

    • [‘A’, ‘B’, ‘C’, ‘a’, 1]
    lst = ['A', '', 'B', None, 'C', ' ', 'a', 1, 0]
    print(list(filter(lambda x:x and str(x).strip(), lst)))
    # 判断x是否为真
    

3. sorted排序函数

sorted只能给相同类型的数据排序

  • 列表排序

    lst = [-6, 3, 2, -9, 7]
    lst.sort()  # 会改变原来的列表
    print(lst)  # [-9, -6, 2, 3, 7]
    
    lst1 = lst.copy()
    lst1.sort()
    print(lst, lst1)
    
    • 默认是升序,怎么按指定条件排序

      print(sorted(lst, key=abs))
      
    • 排序类型

      lst2 = [True, len(lst)>2, 0, 2]
      print(sorted(lst2))  # [0, True, True, 2]
      
      # lst3 = [1, 5, 'a', 7]
      # print(sorted(lst3))  # TypeError: '<' not supported between instances of 'str' and 'int'
      
  • 列表里包元组的形式排序
    先按照第一个值进行排序,第一个值都一样就按照第二个值进行排序,以此类推

    lst = [(True, True, False),
           (2, 1, 3), (2, 2, 4),
           (False, True, 2),
           (False, False, 3)]
    print(sorted(lst))
    

练习

  1. 列表的值忽略大小写排序
    a => 98;A => 65
lst = ['a', 'A', 'f', 'G', 'd']
print(sorted(lst, key=lambda x:x.lower()))
# print(sorted(lst, key=str.upper))
  1. d1 = {“a”:3, “b”:2, “c”:4, “d”:1} value值来排序
d1 = {"a":3, "b":2, "c":4, "d":1}
# print(d1.items())
# dict_items([('a', 3), ('b', 2), ('c', 4), ('d', 1)])
print(sorted(d1.items(), key=lambda x:x[1]))  # {'d': 1, 'b': 2, 'a': 3, 'c': 4}

用python实现cat access.log |grep alibaba |sort|uniq -c |sort -nr |head -10

count1 = {}
with open("access.log", "r+", encoding="utf-8") as fp:
    for line in fp:
        if "alibaba" in line:
            count1[line] = count1.get(line, 0) + 1
sorted_c = sorted(count1.items(), key = lambda x:x[1],reverse=True)[:10]
print(sorted_c)

4.reduce函数

  • 累计、累加、累除
  • reduce把结果继续和序列的下一个元素做累积计算
from functools import reduce
a = [1, 2, 3, 4]
def func1(x,y):
    return x * 10 + y
print(reduce(func1, a))

练习

  • lst = [‘a’, ‘1’, ‘2bb’, ‘234’, ‘’, ‘9’]

    使用reduce 取出lst里的数字 => 12349

    lst = ['a', '1', '2bb', '234', '', '9']
    from functools import reduce
    def func1(x,y):
            return x + y
    print(reduce(func1, list(filter(lambda x:x.isdigit(), lst))))
    
  • 有以下列表:list1 = [7, -8, 5, 4, 0, -2, -5]

    • 正数在前负数在后
    • 正数从小到大
    • 负数从大到小
    list1 = [7, -8, 5, 4, 0, -2, -5]
    # print(sorted(list1, key=lambda x:max(list1)-x+1))
    print(sorted(list1, key=lambda x:(x<=0,abs(x))))
    
  • 这是一个字符串排序,排序规则:小写<大写<奇数<偶数

    • s = ‘asdf234GDSdsf23’ => 排序:小写-大写-奇数-偶数
    • 原理:先比较元组的第一个值,FALSE
    s = 'asdf234GDSdsf23'
    print(sorted(s, key=lambda x:(x.isdigit(),x.isupper(),x.isdigit() and int(x)%2==0,x)))
    # (False,False,False,'a')
    

    先将字符串分为前面是字母,后面是数字(用sorted排序,True在后,False在前)

    同理,再对数字进行奇偶数的排序,对字母进行大小写的排序


总结

本章介绍了主要的几个高阶函数的使用与主要格式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值