每一次对过程的重复称为一次 迭代,而每一次迭代得到的结果作为下一次迭代的初始值。
可迭代对象 Iterable
- 定义:具有__iter__函数的对象,可以返回迭代器对象
- 语法
创建:
class 可迭代对象名称:
def__iter__
(self):
return 迭代器 - 原理
迭代器 = 可迭代对象.__iter__
()
while True:
try:
print(迭代器.__next__
())
except StopIteration:
break - 示例
tuple1 = ("铁扇公主", "铁锤公主", "扳手王子")
iterator = tuple1.__iter__()
while True:
try:
print(iterator.__next__())
except StopIteration:
break
dict1 = {"铁扇公主": 101, "铁锤公主": 102, "扳手王子": 103}
iterator = dict1.__iter__()
while True:
try:
item = iterator.__next__()
print(item, dict1[item], sep="--")
except StopIteration:
break
迭代器 Iterator
"""
迭代器
"""
class Skill:
pass
class SkillIterator:
def __init__(self, target):
self.__target = target
self.__index = 0
def __next__(self):
if self.__index > len(self.__target)-1:
raise StopIteration
# 返回下一个数据
temp = self.__target[self.__index]
self.__index += 1
return temp
class SkillManager:
def __init__(self):
self.__skills = []
def add_skill(self, skill):
self.__skills.append(skill)
def __iter__(self):
# 创建一个迭代器对象,并传递需要迭代的数据
return SkillIterator(self.__skills)
manager = SkillManager()
manager.add_skill(Skill())
manager.add_skill(Skill())
manager.add_skill(Skill())
for item in manager:
print(item)
iterator = manager.__iter__()
# for循环原理实现
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
- 自定义实现range
class MyRange:
def __init__(self, number):
self.__number = number
def __iter__(self):
return MyRangeIterator(self.__number)
class MyRangeIterator:
def __init__(self, n):
self.__n = n
self.__index = 0
def __next__(self):
if self.__index > self.__n - 1:
raise StopIteration
temp = self.__index
self.__index += 1
return temp
for item in MyRange(10):
print(item)
生成器 Generator
定义:能够动态提供数据的可迭代对象
作用:在循环过程中,按照某种算法推算数据,不必创建容器存储完整的结果,从而节省内存。数据量越大,优势越明显
生成器函数
定义:含有yield
语句的函数,返回值为生成器对象
语法:
def 函数名():
…
yield 数据
…
class MyRange:
def __init__(self, number):
self.__number = number
def __iter__(self):
# return MyRangeIterator(self.__number)
number = 0
# yield作用:将下列代码改为迭代器模式
# 生成规则
# 1.将yield以前的语句定义在next方法中
# 2.将yield后面的数据作为next方法返回值
while number < self.__number:
yield number
number += 1
# next一次,计算一次,返回一次
for item in MyRange(10):
print(item)
myrange = MyRange(10)
iterator = myrange.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
class SkillData:
def __init__(self, id, name, atk_ratio, duration):
self.id = id
self.name = name
self.atk_ratio = atk_ratio
self.duration = duration
def __str__(self):
return "%d %s %d %d" % (self.id, self.name, self.atk_ratio, self.duration)
list_skill = [
SkillData(101, "乾坤大挪移", 5, 10),
SkillData(102, "降龙十八掌", 7, 10),
SkillData(103, "葵花宝典", 8, 10),
]
def find01():
for item in list_skill:
if item.atk_ratio > 6:
yield item
for item in find01():
print(item)
enumerate函数
for index,value in enumerate(可迭代对象):
zip函数
for 元组 in zip(iterable1,iterable2,…):
生成器表达式
变量 = (
item for item in 可迭代对象 if 条件)