【发布时间】:2014-10-23 16:40:29
【问题描述】:
我需要在某些输出中找到某一行。我可以这样做,但是在找到输出的正确部分后,我需要在该部分之前提取某些行。
for i, line in enumerate(lines):
target = str(self.ma3) # set target string
if target in line:
print i, line # this gets the correct line, I can stick it in a variable and do stuff with it
i = i - 4 # now I want the line 4 lines before the initial target line
print lines[i] # doesn't work, gives error: TypeError: 'generator' object has no attribute '__getitem__'
如果有人知道如何做到这一点,我们将不胜感激!
【问题讨论】:
-
你是如何创建线条的?您也可以只使用
lines[i-4] -
lines = 我调用的进程的终端输出。我尝试了你的建议,但得到了同样的错误。
-
我并不是说它会起作用,我的意思是在下面的答案中添加你不需要使用
i = i - 4你可以使用lines[i-4]
标签: python string enumerate readlines