### 迭代器 : 能被next调用,并不断返回下一个值得对象,叫做迭代器 (迭代器是对象)
“”"
概念:迭代器指的是迭代取值的工具,迭代是一个重复的过程,每次重复都是基于上一次的结果而继续,单纯的重复不是迭代
特征:不依赖索引,通过next指针迭代所有数据,一次只取一个,可以大大节省空间,迭代无限量的数据
“”"
(1) 可迭代对象
“”"
如果成员中含有__iter__这个方法,就是可迭代对象
dir 函数可以查看一个对象中所有的成员
“”"
setvar = {“a”,1,“b”,2}
for i in setvar:
print(i)
res = dir(setvar)
print(res)
(2) 迭代器
“”"
1.for 循环遍历数据的底层实现就是利用了迭代器,通过next方法进行调用,从而获取数据
可迭代对象 和 迭代器之间的关系: 从不可被直接获取 => 可被直接获取的过程
2.如果是一个可迭代对象,不一定是一个迭代器
如果是一个迭代器,一定是一个可迭代对象
“”"
(1) 如何定义一个迭代器
“”"
(1)iter(可迭代对象)
(2)可迭代对象.iter()
“”"
setvar = {“a”,1,“b”,2}
it = iter(setvar)
print(it) # iterator
(2) 如何判断一个迭代器
“”"
如果内置成员中 含有 iter 和 next 两个方法,就可以判断是一个迭代器
“”"
print(dir(it))
res = “iter” in dir(it) and “next” in dir(it)
print(res)
(3) 如何调用一个迭代器
“”"
(1) next(迭代器)
(2)迭代器.next()
迭代器通过next方法调用时,是单向不可逆的过程
“”"
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
(4) 重置迭代器
“”“next调用,单项不可逆,一条路走到黑”""
it = iter(setvar)
res = next(it)
print(res)
(5) 使用Iterator 和 Iterable 来判断是否是迭代器
“”"
from 从哪里… import 引入
Iterator 迭代器类型 Iterable 可迭代对象
“”"
from collections import Iterator,Iterable
判断setvar的迭代属性
setvar = {“a”,“b”,“c”}
res = isinstance(setvar,Iterator)
print(res) # False
res = isinstance(setvar, Iterable)
print(res) # True
判断range的迭代属性
it = iter(range(5))
res = isinstance(it,Iterator)
print(res)
res = isinstance(it,Iterable)
print(res)
更多的调用方式
1.通过next获取迭代器中的数据
res = next(it)
res = next(it)
res = next(it)
res = next(it)
res = next(it)
res = next(it) error
print(res)
2.通过for循环,遍历迭代器
print("<========>")
it = iter(range(6))
for i in it:
print(i)
3.for 和 next 配合调用迭代器
it = iter(range(100000))
for i in range(10):
res = next(it)
print(res)
print("<===>")
for i in range(10):
res = next(it)
print(res)
### 高阶函数 : 能够把函数当成参数传递的就是高阶函数 map filter reduce sorted
map
“”"
map(func,iterable)
功能:把iterable里面的数据一个一个拿出来,放到func函数中进行处理,把处理的结果扔到迭代器中,返回迭代器
参数:
func 自定义函数 或者 内置函数
iterable 可迭代对象 (容器类型数据 range 迭代器)
返回值:
迭代器
“”"
### 1. [“1”,“2”,“3”,“4”] => [1,2,3,4]
常规:
lst = [“1”,“2”,“3”,“4”]
lst_new = []
for i in lst:
res = int(i)
lst_new.append(res)
print(lst_new)
map改写
from collections import Iterator , Iterable
it = map(int,lst)
res = isinstance(it,Iterator)
print(res)
(1) next 获取迭代器中的元素
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
StopIteration error
res = next(it)
print(res)
(2) for 获取迭代器中的元素
print("<=======>")
it = map(int,lst)
for i in it:
print(i)
(3) for + next 获取迭代器中的元素
it = map(int,lst)
for i in range(2):
print( next(it) )
(4) list 强转迭代器 ,返回一个列表
it = map(int,lst)
lst = list(it)
print(lst)
“”"
代码解析:
首先拿出列表当中的"1",扔到int函数当中处理,处理的结果扔到迭代器当中
首先拿出列表当中的"2",扔到int函数当中处理,处理的结果扔到迭代器当中
首先拿出列表当中的"3",扔到int函数当中处理,处理的结果扔到迭代器当中
首先拿出列表当中的"4",扔到int函数当中处理,处理的结果扔到迭代器当中
最后把迭代器返回
“”"
### 2. [1,2,3,4] => [1,4,9,16]
常规:
lst = [1,2,3,4]
lst_new = []
for i in lst:
res = i ** 2
lst_new.append(res)
print(lst_new)
map 方法一
def func(n):
return n ** 2
it = map(func,lst)
map 方法二
it = map( lambda n : n ** 2 , lst )
强转成列表,瞬间拿到所有数据
print(list(it))
### 3. dic = {97:“a”,98:“b”,99:“c”} 给你[“a”,“b”,“c”] => 返回 [97,98,99]
lst = [“a”,“b”,“c”]
dic = {97:“a”,98:“b”,99:“c”}
dic = {“a”:97,“b”:98,“c”:99}
1.将字典的键值对进行翻转
dic_new = {}
for k,v in dic.items():
# print(k,v)
dic_new[v] = k
print(dic_new)
2.去获取键所对应的值
lst_new = []
for i in lst:
res = dic_new[i]
# 插入到新的列表里
lst_new.append(res)
print(lst_new) # [97, 98, 99]
map改写
print("<=====>")
lst = [“a”,“b”,“c”]
dic = {97:“a”,98:“b”,99:“c”}
方法一
def func(n):
dic_new = {}
for k,v in dic.items():
dic_new[v] = k
return dic_new[n]
it = map(func,lst)
print(list(it))
方法二
def func(n):
for k,v in dic.items():
if n == v:
return k
it = map(func,lst)
print(list(it))
### filter
“”"
filter(func,iterable)
功能:
在自定义的函数中,过滤数据
如果返回True 代表保留数据
如果返回False 代表舍弃该数据
参数:
func 自定义函数
iterable 可迭代性数据(容器类型数据 range对象 迭代器)
返回值:
迭代器
“”"
from collections import Iterator,Iterable
1.[1,2,3,4,5,6,7,8] => 要所有的奇数
常规
lst = [1,2,3,4,5,6,7,8]
lst_new = []
for i in lst:
if i % 2 == 1:
lst_new.append(i)
print(lst_new)
filter 改写
def func(n):
if n % 2 == 0:
return False
else:
return True
it = filter(func,lst)
res = isinstance(it,Iterator)
print(res)
1.next
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
res = next(it)
print(res)
error StopIteration
res = next(it)
print(res)
2.for
it = filter(func,lst)
for i in it:
print(i)
3.for + next
it = filter(func,lst)
for i in range(2):
print(next(it))
4.list强转,瞬间得到所有数据
lst = list(it)
print(lst)
改写成lambda 表达式
lst = [1,2,3,4,5,6,7,8]
print("<===>")
it = filter(lambda n : True if n % 2 == 1 else False , lst)
print(list(it))
### reduce
“”"
reduce(func,iterable)
功能:一次性从iterable当中拿出2个值,扔到func函数中进行处理,
把运算的结果在和iterable的第三个值继续扔到func中做运算
… 以此类推
最后返回计算的结果
参数:
func 自定义函数
iterable 可迭代性数据(容器类型数据 range对象 迭代器)
返回值:
最后计算的结果
“”"
### (1) [5,4,8,8] => 5488
方法一
lst = [5,4,8,8]
strvar = “”
for i in lst:
strvar += str(i)
print(strvar , type(strvar))
intvar = int(strvar)
print( intvar , type(intvar))
方式二
it = iter(lst)
num1 = next(it)
num2 = next(it)
print(num1)
print(num2)
total = 5 * 10 + 4
total = num1 * 10 + num2
54
print(total)
for i in it:
# 54 * 10 + 8 -> 548 * 10 + 8 -> 5488
total = total * 10 + i
print(total , type(total) )
“”"
5 * 10 + 4 => 54
54 * 10 + 8 => 548
548 * 10 + 8 => 5488
“”"
reduce 进行改写
from functools import reduce
lst = [5,4,8,8]
def func(x,y):
return x*10 + y
res = reduce(func,lst)
print(res, type(res))
“”"
先从lst拿出前两个数据,5和4,扔到func当中进行运算 5 * 10 + 4 = 54
拿54 和 容器中第三个元素 8 , 扔到func当中进行运算 54 * 10 + 8 = 548
拿548 和 容器中第四个元素 8 , 扔到func当中进行运算 548 * 10 + 8 = 5488
最后把5488 直接返回,程序结束.
“”"
优化成lambda表达式写法
print( reduce(lambda x,y : x * 10 + y,lst) )
(2) “789” => 789 (禁止使用int)
def func(x,y):
return x*10 + y
def func_int(n):
dic = {“0”:0,“1”:1,“2”:2,“3”:3,“4”:4,“5”:5,“6”:6,“7”:7,“8”:8,“9”:9}
return dic[n]
it = map(func_int,“789”)
print( list(it) ) [7,8,9]
res = reduce(func,it)
print(res, type(res))
“”"
error:
strvar = “789”
res = reduce(func , list(strvar) )
print(res , type(res))
第一次:“7” * 10 + “8” = “77777777778”
第二次:“77777777778” * 10 + 9
777777777787777777777877777777778777777777787777777777877777777778777777777787777777777877777777778777777777789 <class ‘str’>
“”"
### sorted
“”"
sorted(iterable,reverse=False,key=函数)
功能: 排序
参数:
iterable 可迭代性数据(容器类型数据 range对象 迭代器)
reverse 代表是否倒序 reverse=True 代表倒序 从大到小 reverse = False 代表正序,从小到大
key 自定义函数 或 内置函数
返回值:
排序后的列表
“”"
(1) 默认从小到大排序 : 返回新的列表
排序列表
container = [100,200,13,-6,0]
排序元组
container = (100,200,13,-6,0)
排序集合
container = {100,200,13,-6,0}
字符串(按照ascii编码排序)
container = “oneal”
字典 (默认排序的是键)
container = {“a”:1,“b”:2,“c”:3}
lst_new = sorted(container)
print(lst_new)
(2) 从大到小排序
lst_new = sorted(container,reverse=True)
print(lst_new)
(3) 通过内置函数排序
按照绝对值排序 abs
print(abs(-200))
lst = [-200,-300,9,20]
res = sorted(lst,key=abs)
print(res)
(4) 通过自定义函数进行排序
lst = [19,11,15,57]
def func(n):
return n%10
res = sorted(lst,key = func)
print(res)
res = sorted(lst,key = lambda n:n%10)
print(res)
“”"
35 % 10 => 5
27 % 10 => 7
48 % 10 => 8
19 % 10 => 9
“”"
“”"
总结:
sort 基于原有的列表进行排序,只限定列表类型
sorted 所有的容器类型数据都能排,返回一个全新的列表 (推荐)
“”"