Chinaunix首页 | 论坛 | 博客
  • 博客访问: 54313
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-12 22:36
文章分类

全部博文(13)

文章存档

2014年(13)

我的朋友

分类: Python/Ruby

2014-09-15 11:26:13

刚刚看了一下Python里面的enumerate的部分, enumerate每次回返回一个tuple, (index, value)
例子很简单:
for i, v in enumerate(['tic', 'tac', 'toe']):
    print i,v
0 tic
1 tac
2 toe
在enumerate里面我们可以放置一个iterable的对象,这样的对象可以是a sequence, an iterator, or some other object which supports iteration。在Python doc 里面看到这样的解释之后我便尝试自己实现一个iterable的对象。实现如下:
class Enumerable:
    def __init__(self):
        self.value = 1
    def __iter__(self):
        return self
    def next(self):
        if (self.value > 10):
            raise StopIteration
        else:
            self.value += 1
            return self.value


enum = Enumerable()
for i, v in enumerate(enum):
    print i, v
只需要实现__iter__和next接口就可以了
阅读(1703) | 评论(0) | 转发(0) |
0

上一篇:python 大小写

下一篇:mac更新python版本

给主人留下些什么吧!~~