我得到了一个名为'datafile'的文件,其中包含如下数据:
tag
12
22
33
tag
234
1
23
43
tag
8
tag
0
12
“标签”之间的数字不同。
我需要做的是在“tag”之后访问每个第一个(或第二个)数字(如果存在)。
我未完成的Python代码:
f = open('datafile', 'r')
for line in f.readlines():
line = line.strip()
if line == 'tag':
print('tag found!')
# how can I access next number here?
如何进入for循环内的下一行?
答案 0 :(得分:0)
使用馈入发电机的迭代器。
def getFirstSecond(browser):
for line in browser:
line = line.strip()
if line == 'tag':
first = next(browser).strip()
try:
second = next(browser).strip()
except StopIteration:
second = None
yield first, second if second != 'tag' else first, None
with open('datafile', 'r') as f:
browser = iter(f)
pairs = list(getFirstSecond(browser))
要回答您的问题,请使用next
功能继续下一行。
注意使用with
语句;这是你应该如何打开一个文件(它确保文件在你完成后关闭)。
答案 1 :(得分:0)
每次遇到"标记"
时,重置计数器会更容易k = 1 # or 2, or whatever
with open('datafile', 'r') as f:
since_tag = 0
for line in f:
line = line.strip()
if line == 'tag':
print('tag found!')
since_tag = 0
if since_tag == k:
print "kth number found: ", line
since_tag += 1