Python迭代器和生成器(高级编程四)

2020-01-04  本文已影响0人  冷煖自知

迭代器

from collections import Iterator, Iterable
# Iterable 为可迭代对象
# Iterator 为迭代器
list=[1,2,3,4] 
it = iter(list) # 讲可迭代对象(数组)转为迭代器

print(next(it))
print(next(it))
print(next(it))


>> 1
>> 2
>> 3
class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration


myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
    print(x)

生成器

import sys
 
def fibonacci(n): # 生成器函数 - 斐波那契
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
 
while True:
    try:
        print (next(f), end=" ")
    except StopIteration:
        sys.exit()

生成器如何读取大文件

文件300G,文件比较特殊,一行 分隔符 {|}

def readlines(f,newline):
    buf = ""
    while True:
        while newline in buf:
            pos = buf.index(newline)
            yield buf[:pos]
            buf = buf[pos + len(newline):]
        chunk = f.read(4096*10)
        if not chunk:
            yield buf
            break
        buf += chunk

with open('demo.txt') as f:
    for line in readlines(f, "{|}"):
        print(line)
上一篇 下一篇

猜你喜欢

热点阅读