惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
D
DataBreaches.Net
D
Docker
云风的 BLOG
云风的 BLOG
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
Martin Fowler
Martin Fowler
U
Unit 42
Engineering at Meta
Engineering at Meta
IT之家
IT之家
Vercel News
Vercel News
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
博客园 - Franky
博客园 - 【当耐特】
Stack Overflow Blog
Stack Overflow Blog
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog

博客园 - 老保

不要把MASM32开发环境和MASM汇编器版本搞混了 python获取当前脚本所在目录 mysql 随记 c程序设计语言(第二版) 阅读笔记 九 unix系统IO c程序设计语言(第二版) 阅读笔记 八 文件 c程序设计语言(第二版) 阅读笔记 七 结构和联合 c程序设计语言(第二版) 阅读笔记 六 指针 c程序设计语言(第二版) 阅读笔记 五 变量作用域及变量声明和定义 c程序设计语言(第二版) 阅读笔记 四 函数定义域声明规则 c程序设计语言(第二版) 阅读笔记 三 ANSI C及较早版本函数声明 c程序设计语言(第二版) 阅读笔记 二 变量声明 extern c程序设计语言(第二版) 阅读笔记 一 特点和简介 XMLHttpRequest和W3C DOM备忘 socket 常用的数据结构备忘 笔试题目 NHibernate Configuration和Sessionfactory c# 学习笔记1 (枚举和结构类型和数组) js常用函数 一个很简洁 效果很好的js效果 - 老保 - 博客园
python迭代器
老保 · 2010-05-12 · via 博客园 - 老保

By now, you've probably noticed that most container objects can looped over using a for statement:

现在你可能注意到大多数容器对象都可以用 for 遍历:

for element in [1, 2, 3]:
    print element
for element in (1, 2, 3):
    print element
for key in {'one':1, 'two':2}:
    print key
for char in "123":
    print char
for line in open("myfile.txt"):
    print line

This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate. This example shows how it all works:

这种形式的访问清晰、简洁、方便。这种迭代器的用法在 Python 中普遍而且统一。在后台,for 语句在容器对象中调用 iter() 。 该函数返回一个定义了 next() 方法的迭代器对象,它在容器中逐一访问元素。没有后续的元素时,next() 抛出一个 StopIteration 异常通知 for 语句循环结束。以下是其工作原理的示例:

>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> it.next()
'a'
>>> it.next()
'b'
>>> it.next()
'c'
>>> it.next()

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in -toplevel-
    it.next()
StopIteration

Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self:

了解了迭代器协议的后台机制,就可以很容易的给自己的类添加迭代器行为。定义一个 __iter__() 方法,使其返回一个带有 next() 方法的对象。如果这个类已经定义了 next(),那么 __iter__() 只需要返回self:

>>> class Reverse:
    "Iterator for looping over a sequence backwards"
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

>>> for char in Reverse('spam'):
    print char