# 生成器函数,函数里只要有yield 关键字
def gen_func():
yield 1
yield 2
yield 3
# 斐波拉契(当位数等于前两位数之和) 0 1 1 2 3 5 8
# 惰性求值 ,掩饰求值提供
# 只返回当位的值
def fib(index):
if index <= 2:
return 1
else:
return fib(index-1) +fib(index-2)
print(fib(5))
# 返回当位前面所有的值
def fib1(index):
re_list = []
n,a,b = 0,0,1
while n<index:
re_list.append(b)
a,b = b,a+b
n+=1
return re_list
print(fib1(50))
# 生成器完成
def gen_fib(index):
n, a, b = 0, 0, 1
while n < index:
yield b
a, b = b, a + b
n += 1
for data in gen_fib(10):
print(data)
if __name__ == '__main__':
gen = gen_func()
for value in gen:
print(value)
读大文件案例
def myreadlines(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)
if not chunk:
# 说明已经读到了文件结尾
yield buf
break
buf+=chunk
with open("input.txt") as f:
for line in myreadlines(f,"{|}"):
print(line)
标签:chunk,newline,生成器,pos,yield,buf From: https://www.cnblogs.com/niunai/p/16884712.html