关于python的菜鸟问题,望大神解答
deflines(file):forlineinfile:yieldlinedefblocks(file):block=[]forlineinlines(file):if...
def lines(file):
for line in file: yield line
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
用这些代码创建文本块,然后调用输出时,为何会丢掉最后一块 展开
for line in file: yield line
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
用这些代码创建文本块,然后调用输出时,为何会丢掉最后一块 展开
1个回答
展开全部
你应该是没考虑到最后一行不是空白行的情况,这样最后一行就无法根据判断条件yield了,你可以在后面加一句话测试下,如下:
def lines(file):
for line in file: yield line
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
print(len(block))
def lines(file):
for line in file: yield line
def blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
print(len(block))
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询