由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - Python大牛请进
相关主题
(求推荐)recursion以及把recursion转变为iteration的资料面试时 迭代还是递归
昨天的google面试题L家的高频题merge k sorted arrays giving iterators求讨论!
[合集] 昨天的google面试题Uber新题
图的随机访问reverse an array
请教一个新鲜算法面试题新鲜出炉的Google电面面经,求祝福
请教将任意递归问题转换为尾递归的方法问道G 的题
我发现我竟然学会了12种tree traversal的办法没看懂Leetcode这道题的答案,请指点
请问怎样写没有parent pointer的BST iterator?发个g的电面
相关话题的讨论汇总
话题: input话题: func话题: list话题: readlines话题: yield
进入JobHunting版参与讨论
1 (共1页)
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

1 (共1页)
进入JobHunting版参与讨论
相关主题
发个g的电面请教一个新鲜算法面试题
求yelp内推请教将任意递归问题转换为尾递归的方法
看到一个题目我发现我竟然学会了12种tree traversal的办法
问个stl的iterator问题请问怎样写没有parent pointer的BST iterator?
(求推荐)recursion以及把recursion转变为iteration的资料面试时 迭代还是递归
昨天的google面试题L家的高频题merge k sorted arrays giving iterators求讨论!
[合集] 昨天的google面试题Uber新题
图的随机访问reverse an array
相关话题的讨论汇总
话题: input话题: func话题: list话题: readlines话题: yield