热线电话:13121318867

登录
2018-12-13 阅读量: 775
Python中怎么实现迭代?

python中的迭代器是任何可以与'for in循环'一起使用的python类型。Python列表,元组,dicts和集都是内置迭代器的示例。这些类型是迭代器,因为它们实现以下方法。实际上,任何想要成为迭代器的对象都必须实现以下方法。

  1. 在初始化迭代器时调用的__iter__方法。这应该返回一个具有next或__next __(在Python 3中)方法的对象。
  2. next(Python 3中的__next__)迭代器next方法应返回iterable的下一个值。当迭代器与'for in'循环一起使用时,for循环隐式调用迭代器对象上的next()。此方法应引发StopIteration以指示迭代结束。

下面是一个简单的Python程序,它创建迭代器类型,从10迭代到给定限制。例如,如果限制为15,则打印10 11 12 13 14 15.如果限制为5,则不打印任何内容

# A simple Python program to demonstrate

# working of iterators using an example type

# that iterates from 10 to given value

# An iterable user defined type

class Test:

# Cosntructor

def __init__(self, limit):

self.limit = limit

# Called when iteration is initialized

def __iter__(self):

self.x = 10

return self

# To move to next element. In Python 3,

# we should replace next with __next__

def next(self):

# Store current value ofx

x = self.x

# Stop iteration if limit is reached

if x > self.limit:

raise StopIteration

# Else increment and return old value

self.x = x + 1;

return x

# Prints numbers from 10 to 15

for i in Test(15):

print(i)

# Prints nothing

for i in Test(5):

print(i)

0.0000
4
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子