"""
什么叫迭代器?
实现了迭代协议的对象,叫做迭代器
实现迭代协议:
__next__: 返回下一个元素 next(obj)=> obj.__next__()
__iter__: 返回迭代对象本身
"""
# 实现输出0-9=》 range(10)
# range(10) => MyIterator(10) => 0-9
# 容器:字典,列表
class MyIterator:
def __init__(self, num):
self.num = num
self.cursor = 0
# self.container = []
def __next__(self):
if self.cursor < self.num:
data = self.cursor
self.cursor += 1
return data
else:
raise StopIteration
def __iter__(self):
return self
def __getitem__(self, item): # getitem => 根据item去获取条目
return 1 # 通过下标去获取元素
# for i in MyIterator(10):
# print(i)
#
# for i in range(10):
# print(i)
# data = MyIterator(10)
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
# print(next(data))
for i in MyIterator(10):
print(i)
# for i in MyIterator(10): => 先执行的是MyIterator(10) => MyIterator对象
# for循环=> 迭代器 => __iter_
# for循环去调用__next__方法, 去执行for循环中的语句
# 又回到for循环
# 自己定义一个MyIterator, 实现range的功能
# # range(start, stop, step) => MyIterator
# # range(10) # start=0, stop=10, step=1
# # rang(10) # range(start=0, stop, step=1) =>start=10
# # range(0,10)
# # range(0,10,2)
# # MyIterator(10)
# # MyIterator(0,10)
# # MyIterator(0,10,2)
# for i in range(10):
# print(i)
# for i in range(1, 10):
# print(i)
# for i in range(1, 10, 2):
# print(i)
list_data = [1, 2, 3, 4, 5]
list()
print(list_data[0]) #本质是什么?
# MyIterator[0]
data = MyIterator(10)
# print(data[0])
# print(data[1])
# print(data[2])
# print(data[3])
print(list(range(10)))
print(list(MyIterator(10)))
# 生成器内部实现了迭代协议:意味者就实现了__next__和__iter__方法
# 所以生成器是可迭代的
# 生成器表达式:
# def func():
# yield 1
#
# gen = func()
# 另一种定义生成器:(表达式 for 临时变量 in iterable 过滤)
gen = (i for i in range(1, 11))
print(gen, type(gen))
for i in gen:
print(i)
Python(iterator_learning)
最新推荐文章于 2024-08-26 18:56:03 发布