迭代器 iter()

在python中,所有集合都可以迭代,迭代器支持以下:

for循环

构建和扩展组合类型

逐行便利文本文件

列表推导、字典或集合推导

元组拆包

调用函数时,使用*拆包实参

import re, reprlib
from collections import abc

RE_WORD = re.compile('\w+')
class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = RE_WORD.findall(text)
    def __getitem__(self, index):
        return self.words[index]
    def __len__(self):
        return len(self.words)
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)
    # def __iter__(self):
    #     return self
def y():
    s = Sentence('"The time has come," the Walrus said,')
    # TODO
    print(s)  # Sentence('"The time ha... Walrus said,')  ???
    for word in s:
        print(word)

    print(list(s))
    print(type(s))
    print(s[1])
    print(isinstance(s, abc.Iterable))
    m = iter(s) # 从s中获得迭代器
    print(next(m))

 判断是否可迭代:

isinstance(s, abc.Iterable) # 仅判断是否有__iter__()函数
iter(x) # 如果有__getitem__()函数也可迭代。如果不可迭代需要处理异常TypeError

 可迭代和迭代器:

 

 使用说明

迭代器只有以上两个方法,除了调用next()和捕获StopIteration异常,没有办法检查是否有遗留元素,如果要再次迭代,需要调用iter(可迭代对象)

def m():
    s3 = Sentence('pig and pepper')
    it = iter(s3)  #从s3中获取迭代器
    next(it)
    next(it)
    next(it) # pepper
    next(it) # Traceback...StopIteration
    list(it) #[] it迭代器已经空了
    list(iter(s3)) #重新构造迭代器

 把Sentence变成迭代器:坏主意 

import re, reprlib
from collections import abc

RE_WORD = re.compile('\w+')
class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = RE_WORD.findall(text)
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)
    def __iter__(self):
        return SentenceIterator(self.words)
class SentenceIterator:
    def __init__(self, words):
        self.words = words
        self.index = 0
    def __next__(self):
        try:
            word = self.words[self.index]
        except IndexError:
            raise StopIteration()
        self.index += 1
        return word
    def __iter__(self):
        return self


def y():
   s = Sentence('pig and dog')
   it = iter(s)
   print(next(it))
   print(next(it))
   print(next(it))
   print(next(it))
y()

 

 【反模式】

import re, reprlib
from collections import abc

RE_WORD1 = re.compile('\w+')
class Sentence1:
    def __init__(self, text):
        self.text = text
        self.words = RE_WORD1.findall(text)
        self.index = 0
    def __next__(self):
        try:
            word = self.words[self.index]
        except IndexError:
            raise StopIteration()
        self.index += 1
        return word
    def __iter__(self):
        return self
    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)

def xs():
    s = Sentence1('PIG AND DOG')
    ss = Sentence1('1PIG 1AND 1DOG')
    print(isinstance(s, abc.Iterator))
    print(next(s))
    print(next(ss))
xs()

使用生成器替代迭代器

生成器 代替迭代器 yield_gtestcandle的博客-CSDN博客111https://blog.csdn.net/gtestcandle/article/details/120457315

以iter(o)的形式调用返回的是迭代器,以iter(func, sentinel)的形式调用,能使用任何函数构建迭代器。

import random
def d6():
    return random.randint(1,6)
d6_iter = iter(d6, 1)
print(d6_iter)
[print(roll) for roll in d6_iter]

python3的iter()语法_齐梦星空-CSDN博客一. iter()的标准用法:iter(object)object:必须是支持迭代的集合对象question:如何判断一个对象是否可迭代?from collections import Iterableisinstance(object,Iterable)question:定义一个可迭代对象?需要在class里实现一个 def iter(self)方法,该方法的返回值是一...https://blog.csdn.net/weixin_37275456/article/details/90404761

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值