自定义迭代器:
""""""
"""
练习:参照下列代码,自定义MyRange类,实现以下效果。
for item in range(5):
print(item)# 0 1 2 3 4
for item in MyRange(5):
print(item)# 0 1 2 3 4
"""
# 1------------------------
class MyRangeIterator:
"""
技能迭代器
"""
def __init__(self,stop):
self.stop=stop
self.count = 0
def __next__(self):
# 如果索引越界 则停止迭代
if self.count >= self.stop:
raise StopIteration()
temp=self.count
self.count += 1
return temp
class MyRange:
def __init__(self,stop):
self.stop=stop
def __iter__(self):
# 1. 创建迭代器对象
# 2. 传递需要迭代的数据
return MyRangeIterator(self.stop)
for item in MyRange(5):
print(item)
# while 调用
manager = MyRange(5)
iterator = manager.__iter__()
# 使用迭代器获取manager中的技能列表
while True:
try:
item = iterator.__next__()
print(item)
except:
break
# 2------------------------
class MyRange:
def __init__(self,stop):
self.stop=stop
def __iter__(self):
count = 0
while count < self.stop:
yield count
count += 1
for item in MyRange(5):
print(item)
# 3--------------------
def my_range(stop):
count = 0
while count < stop:
yield count
count += 1
for item in my_range(5):
print(item)
迭代器------生成器:
"""
迭代器
"""
class Skill:
pass
class SkillManager:
def __init__(self, skills):
self.skills = skills
def __iter__(self):
# 解释器检测到yield关键字,就会生成迭代器对象。
# 自动生成迭代器的大致规则
# 1、yield关键字以前的代码会放到__next__方法中
# 2、yield关键字以后的数据会作为__next__方法的返回值
print("11111")
yield self.skills[0]
print("22222")
yield self.skills[1]
print("33333")
yield self.skills[2]
manager = SkillManager([Skill(), Skill(), Skill()])
# for item in manager:
# print(item)
iterator = manager.__iter__()
# # 使用迭代器获取manager中的技能列表
while True:
try:
item = iterator.__next__()
print(item)
except:
break
def my_range(stop):
count = 0
while count < stop:
yield count
count += 1
for item in my_range(5):
print(item)
"""
定义一个enumerate 生成器
"""
list01 = ["a", "b", "c", "d", "e"]
def my_enumerate(list_en):
count = 0
while count < len(list_en):
yield (count, list_en[count])
count += 1
for item in my_enumerate(list01):
print(item)
for index, item in my_enumerate(list01):
print(index, item)
"""
定义一个zip 生成器:
将多个可迭代对象元素组合成一个个元组
"""
list01 = ["a", "b", "c", "d", "e"]
list02 = ["A", "B", "C", "D", "E"]
def my_zip(list_01, list_02):
count = 0
while count < len(list_01):
yield (list_01[count], list_02[count])
count += 1
for item in my_zip(list01, list02):
print(item)
for index, item in my_zip(list01, list02):
print(index, item)