迭代器 iter()
在python中,所有集合都可以迭代,迭代器支持以下:
for循環(huán)
構(gòu)建和擴(kuò)展組合類(lèi)型
逐行便利文本文件
列表推導(dǎo)、字典或集合推導(dǎo)
元組拆包
調(diào)用函數(shù)時(shí),使用*拆包實(shí)參
import re, reprlib from collections import abcRE_WORD = re.compile('\w+') class Sentence:def __init__(self, text):self.text = textself.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,')# TODOprint(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__()函數(shù) iter(x) # 如果有__getitem__()函數(shù)也可迭代。如果不可迭代需要處理異常TypeError?可迭代和迭代器:
?
?使用說(shuō)明
迭代器只有以上兩個(gè)方法,除了調(diào)用next()和捕獲StopIteration異常,沒(méi)有辦法檢查是否有遺留元素,如果要再次迭代,需要調(diào)用iter(可迭代對(duì)象)
def m():s3 = Sentence('pig and pepper')it = iter(s3) #從s3中獲取迭代器next(it)next(it)next(it) # peppernext(it) # Traceback...StopIterationlist(it) #[] it迭代器已經(jīng)空了list(iter(s3)) #重新構(gòu)造迭代器?把Sentence變成迭代器:壞主意?
import re, reprlib from collections import abcRE_WORD = re.compile('\w+') class Sentence:def __init__(self, text):self.text = textself.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 = wordsself.index = 0def __next__(self):try:word = self.words[self.index]except IndexError:raise StopIteration()self.index += 1return worddef __iter__(self):return selfdef 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 abcRE_WORD1 = re.compile('\w+') class Sentence1:def __init__(self, text):self.text = textself.words = RE_WORD1.findall(text)self.index = 0def __next__(self):try:word = self.words[self.index]except IndexError:raise StopIteration()self.index += 1return worddef __iter__(self):return selfdef __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)的形式調(diào)用返回的是迭代器,以iter(func, sentinel)的形式調(diào)用,能使用任何函數(shù)構(gòu)建迭代器。
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()語(yǔ)法_齊夢(mèng)星空-CSDN博客一. iter()的標(biāo)準(zhǔn)用法:iter(object)object:必須是支持迭代的集合對(duì)象question:如何判斷一個(gè)對(duì)象是否可迭代?from collections import Iterableisinstance(object,Iterable)question:定義一個(gè)可迭代對(duì)象?需要在class里實(shí)現(xiàn)一個(gè) def iter(self)方法,該方法的返回值是一...https://blog.csdn.net/weixin_37275456/article/details/90404761
總結(jié)
以上是生活随笔為你收集整理的迭代器 iter()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Vue组件与动画
- 下一篇: 3.5 基本属性测试