栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 前言
  • 高阶函数
    • 1. map函数
      • 练习
    • 2. filter函数
    • 3. sorted排序函数
      • 练习
  • 用python实现cat access.log |grep alibaba |sort|uniq -c |sort -nr |head -10
    • 4.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)  # 
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在前)

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


总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1011986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号