python實(shí)現(xiàn)迭代器示例

運(yùn)行環(huán)境:2.7.14

構(gòu)造一個(gè)類(lèi)來(lái)輸出固定次數(shù)的字符

類(lèi)來(lái)實(shí)現(xiàn)迭代器的重點(diǎn)是:

  • 有個(gè)__iter__(self)實(shí)例方法,返回實(shí)例本身即可
  • 有個(gè)next(self)實(shí)例方法,返回值
  • python3是用的__next__(self),python2用的是next(self),注意選擇
# -*- coding: utf-8 -*-
'用類(lèi)實(shí)現(xiàn)一個(gè)迭代器'

class Iter(object):

    def __init__(self, value, max_count):
        self.value = value
        self.max_count = max_count
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.max_count:
            raise StopIteration
        self.count += 1
        return self.value

    # 兼容python2系列
    def next(self):
        return self.__next__()

iteration = Iter('hello', 3)
for i in iteration:
    print i

通過(guò)yield來(lái)做個(gè)生成器實(shí)現(xiàn)迭代器

# -*- coding: utf-8 -*-
'結(jié)合yield做一個(gè)生成器,實(shí)現(xiàn)一個(gè)迭代器'

def gen(value, max_count):
    for _ in range(max_count):
        yield value

for _ in gen('hello', 3):
    print _

福利:做個(gè)斐波那契數(shù)列,輸出數(shù)列中10以內(nèi)的數(shù)字吧

# -*- coding: utf-8 -*-
'一個(gè)斐波那契的生成器'

def generat_fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a+b

a = generat_fib()
for i in a:
    if i > 10:
        break
    print i
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容