Python开发【迭代器】

1、迭代器

1.1、迭代器创建:指定数据创建迭代器(使用iter()和next() )

x = [1, 2, 3] #定义一个列表:<class 'list'>
y = iter(x)   #创建一个可迭代对象:<class 'list_iterator'>
#print(next(y)) # 1
#print(next(y)) # 2
#print(next(y)) # 3
#print(next(y)) # 迭代结束会后返回异常StopIteration错误
for i in y:
  print(i,end=" ")
print()

# 1  2  3

1.2、迭代对象:定义魔术方法:__next__()__iter__()

class A:
  def __init__(self):
    self.x=0
  def __next__(self):
    self.x += 1
    if self.x>10:
      raise StopIteration
    return self.x
  def __iter__(self):
    return self

a = A()
print(list(a))
#for i in a:
# print(i)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  

猜你喜欢

转载自www.cnblogs.com/loser1949/p/9509046.html