q****x 发帖数: 7404 | 1 这个yield到底有啥好处?这里的例子怎么省内存了?readlines不还是要读入整个文件
吗?
http://stackoverflow.com/questions/7883962/where-to-use-yield-i
我的理解:
def func_0(input_list):
return [f(i) for i in input_list]
def func_1(input_list):
for i in input_list:
yield f(i)
这两个区别在于,func_0把所有的f(i)算好,返回。func_1创建一个对象,包含input_
list,函数f,迭代子iter。遍历这个对象时,动态计算f(i)。这样看上去只是lazy
evaluation,并没有省内存啊。 |
b*******S 发帖数: 17 | 2 我沒有去看python的code 不過就猜猜看 只是推理
http://docs.python.org/library/stdtypes.html?
highlight=readlines#file.readlines
裡面說Files support the iterator protocol. Each iteration returns the same
result as readline(), and iteration ends when the readline() method returns
an empty string.
所以你stackoverflow裡面的例子
for line in file.readlines():
#preprocess line
yield line
這樣搞不好就是直接弄個iterator來,每次就叫file.readline()去抓一行
如果是這樣的case,那當然就會省空間了 |
q****x 发帖数: 7404 | 3 有可能。不过几百兆的文件读入内存也没啥压力吧。
真要是超级大文件,派送又慢了点。
returns
【在 b*******S 的大作中提到】 : 我沒有去看python的code 不過就猜猜看 只是推理 : http://docs.python.org/library/stdtypes.html? : highlight=readlines#file.readlines : 裡面說Files support the iterator protocol. Each iteration returns the same : result as readline(), and iteration ends when the readline() method returns : an empty string. : 所以你stackoverflow裡面的例子 : for line in file.readlines(): : #preprocess line : yield line
|
p**o 发帖数: 3409 | 4 readlines()会把整个文件读成a list of strings,不会lazy eval
要省空间可以这么写
def get_lines (files):
for f in files:
for line in f:
yield line
【在 b*******S 的大作中提到】 : 我沒有去看python的code 不過就猜猜看 只是推理 : http://docs.python.org/library/stdtypes.html? : highlight=readlines#file.readlines : 裡面說Files support the iterator protocol. Each iteration returns the same : result as readline(), and iteration ends when the readline() method returns : an empty string. : 所以你stackoverflow裡面的例子 : for line in file.readlines(): : #preprocess line : yield line
|