markdown python,练习,语法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown python,练习,语法相关的知识,希望对你有一定的参考价值。
### fab v1, 缺点, 只打印, 不能存储
```
In [68]: def fab(max):
...: n, a, b = 0, 0, 1
...: while n < max:
...: print(b)
...: a, b = b, a+b
...: n += 1
In [72]: fab(5)
1
1
2
3
5
```
### fab v2, 缺点, 如果max 过大, 直接爆内存
```
In [73]: def fab(max):
...: n, a, b = 0, 0, 1
...: L = []
...: while n < max:
...: L.append(b)
...: a, b = b, a+b
...: n += 1
...: return L
...:
In [74]: fab(5)
Out[74]: [1, 1, 2, 3, 5]
```
### fab v4, 缺点, 用class 形式来表示,略显复杂
ps: python 2 中位 def next, 语法有变
```
In [116]: class Fab(object):
...: def __init__(self, max):
...: self.max = max
...: self.n, self.a, self.b = 0, 0, 1
...: def __iter__(self):
...: return self
...: def __next__(self):
...: if self.n < self.max:
...: r = self.b
...: self.a, self.b = self.b, self.a + self.b
...: self.n = self.n + 1
...: return r
...: raise StopIteration()
...:
In [117]: for n in Fab(5):
...: print(n)
...:
1
1
2
3
5
```
### fab v5, yield
```
In [86]: def fab(max):
...: n, a, b = 0, 0, 1
...: while n < max:
...: yield b
...: a, b = b, a+b
...: n = n + 1
...:
In [87]: for n in fab(5):
...: print(n)
...:
1
1
2
3
5
In [90]: ret = fab(5)
In [91]: next(ret)
Out[91]: 1
In [92]: next(ret)
Out[92]: 1
In [93]: next(ret)
Out[93]: 2
In [94]: next(ret)
Out[94]: 3
In [95]: next(ret)
Out[95]: 5
In [96]: next(ret)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-96-2216548e65ed> in <module>()
----> 1 next(ret)
StopIteration:
In [98]: ret = fab(5)
In [99]: ret
Out[99]: <generator object fab at 0x00D11510>
In [100]: list(ret)
Out[100]: [1, 1, 2, 3, 5]
```
值得注意的是 fab 和 fab(5) 的区别, 类似于一个是定义, 一个是实现
```
In [101]: from inspect import isgeneratorfunction
In [102]: isgeneratorfunction(fab)
Out[102]: True
In [104]: import types
In [105]: isinstance(fab, types.GeneratorType)
Out[105]: False
In [106]: isinstance(fab(5), types.GeneratorType)
Out[106]: True
In [107]: from collections import Iterable
In [108]: isinstance(fab, Iterable)
Out[108]: False
In [109]: isinstance(fab(b), Iterable)
Out[109]: True
```
另一种 yield 的使用场景是大文件的读取:
```
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath, 'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
```
[廖大大的解析](https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/)
以上是关于markdown python,练习,语法的主要内容,如果未能解决你的问题,请参考以下文章