常用内置函数以及for循环本质
常用内置函数
1、map() 映射
l = [1,2,3,4] map(lambda x:x+1,l) # 循环获取列表中每个元素并传递给匿名函数保存返回值
2、zip() 拉链
# 第一种 l = [11, 22, 33, 44] name_list = ['jason', 'kevin', 'tony', 'jerry']
# 传统做法 new_list = [] for i in range(len(l)): new_list.append((l[i],name_list[i])) print(new_list) [(11, 'jason'), (22, 'kevin'), (33, 'tony'), (44, 'jerry')]
# zip res = zip(l, name_list,) print(list(res)) # [(11, 'jason'), (22, 'kevin'), (33, 'tony'), (44, 'jerry')] # 第二种 l = [11, 22, 33, 44, 55, 66, 77] name_list = ['jason', 'kevin', 'tony', 'jerry'] res = zip(l, name_list) print(list(res)) # [(11, 'jason'), (22, 'kevin'), (33, 'tony'), (44, 'jerry')] # 第三种 l = [11, 22, 33, 44, 55, 66, 77] name_list = ['jason', 'kevin', 'tony', 'jerry'] l1 = [1, 2, 3, 4, 5, 6, 7] l2 = [8, 7, 6, 4, 3, 2, 1] res = zip(l, name_list, l1, l2) print(list(res)) # [(11, 'jason', 1, 8), (22, 'kevin', 2, 7), (33, 'tony', 3, 6), (44, 'jerry', 4, 4)]
3、max与mix max求最大值,min求最小值
# 1、列表求最大和最小值 l = [11, 22, 33, 44, 55, 66, 77] print(max(l)) # 77 print(min(l)) # 11 # 2、字典求最大和最小值 d = { 'jason':3000, 'Bevin':1000000, 'Ascar':10000000000, 'aerry':88888 }
print(max(d,key=lambda key:d[key])) # for循环先取值 之后再比较大小 # Ascar # 3、匿名函数 print(min(d,key=lambda key:d[key])) # jason
4、filter 过滤
l = [11, 22, 33, 44, 55] res = filter(lambda x: x > 30, l) print(list(res)) # [33, 44, 55]
5、reduce 归总
from functools import reduce d = [11, 22, 33, 44, 55, 66, 77, 88, 99] res = reduce(lambda x, y: x + y, d) # 495 res1 = reduce(lambda x, y: x + y, d, 100) # 595 还可以额外添加元素值 print(res) print(res1)
for循环本质
1、for循环内部原理
1、将关键字in后面的数据先调用_iter_方法转成迭代器对象
2、循环执行_next_方法
3、取完之后_next_会报错,但是for循环会自动捕获该错误并处理
2、伪代码演示
res = 数据.__iter__() while True: 检测代码是否会报错 res.__next__() 如果报错了则自动处理掉并结束while循环
3、代码演示
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] # 原理 # 1.先将列表转为迭代器对象 res = l1.__iter__() # 2.循环执行__next__取值 while True: print(res.__next__()) # for循环 for i in l1: print(i)
4、for循环本质
d = {'name': 'tony', 'pwd': 123, 'hobby': 'read'} res = d.__iter__() while True: try: print(res.__next__()) except StopIteration as e: break