实现斐波那契数列的集中方法
-
返回一个数
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a+b
n += 1 fib(5) -
返回列表
def fib(max):
res = []
n, a, b = 0, 0, 1
while n < max:
res.append(b)
a, b = b, a+b
n += 1
return res
fib(5) -
使用可迭代对象
from collections import Iterator
class Fib(Iterator):
def __init__(self, max):
self.max = max
self.index = 0
self.a = 0
self.b = 1
def __next__(self):
if self.index < self.max:
res = self.b
self.a, self.b = self.b , self.b + self.a
self.index += 1
return res
else:
raise StopIteration # StopIteration()
def __iter__(self):
return self for x in Fib(5):
print(x) -
使用yield 生成器
def fib4(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n += 1 f = fib4(5) for i in range(6):
print('%s: %s' % (i,next(f))) -
yield防止读大文件出现内存不够的问题
def read_by_chunk(filename):
BLOCK_SIZE = 1024
with open(filename, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return -
使用pandas读文件,类似5的操作
import pandas as pd
reader = pd.read_table('AA.csv', chunksize=1024)
for chunk in reader:
print(chunk) -
使用pandas读文件,运行时才制定块大小
import pandas as pd
reader = pd.read_csv('AA.csv', sep='|', iterator=True)
while True:
try:
chunk = reader.get_chunk(5)
print(chunk)
except:
break
```
-
yield生成斐波那契数列的迭代对象
class Fib:
def __init__(self, start, end):
self.start = start
self.end = end
def __iter__(self):
index, a, b = 0, 0, 1
while index < self.start:
a, b = b, a+b
index += 1
while index <= self.end:
yield b
a, b = b, a+b
index += 1 for i in Fib(1,10):
print(i) -
yield生成质数的迭代对象
class PrimeNum:
def __init__(self, start, end):
self.start = start
self.end = end
def is_prime(self, num):
if num < 2:
return False
for i in range(2,num):
if num%i == 0:
return False
return True
def __iter__(self):
for i in range(self.start, self.end):
if self.is_prime(i):
yield i for i in PrimeNum(1, 20):
print(i)
注: 参考了runoob