<p>不能更改<code>enumerate()</code>iterable的计数器,否</p>
<p>你根本不需要在这里,也不需要寻找。而是使用嵌套循环并缓冲节标题:</p>
<pre><code>with open(filename) as fh:
enumerated = enumerate(fh, start=1)
header = None
for lineno, line in enumerated:
# seek to first section
if header is None:
if not line.startswith('#'):
continue
header = line
print("=" * 40)
print(header.rstrip())
for lineno, line in enumerated:
if line.startswith('#'):
# new section
header = line
break
# section line, handle as such
print("[{}] {}".format(lineno, line.rstrip()))
</code></pre>
<p>这只缓冲标题行;每当我们遇到一个新的标题时,它就会被存储起来,当前的节循环就结束了。你知道吗</p>
<p>演示:</p>
<pre><code>>>> from io import StringIO
>>> demo = StringIO('''\
... #HEADER1, SOME EXTRA INFO
... data first section
... 1 2
... 1 233
... ...
... // THIS IS A COMMENT
... #HEADER2, SECOND SECTION
... 452
... 134
... // ANOTHER COMMENT
... ...
... #HEADER3, THIRD SECTION
... ''')
>>> enumerated = enumerate(demo, start=1)
>>> header = None
>>> for lineno, line in enumerated:
... # seek to first section
... if header is None:
... if not line.startswith('#'):
... continue
... header = line
... print("=" * 40)
... print(header.rstrip())
... for lineno, line in enumerated:
... if line.startswith('#'):
... # new section
... header = line
... break
... # section line, handle as such
... print("[{}] {}".format(lineno, line.rstrip()))
...
========================================
#HEADER1, SOME EXTRA INFO
[2] data first section
[3] 1 2
[4] 1 233
[5] ...
[6] // THIS IS A COMMENT
========================================
#HEADER2, SECOND SECTION
[9] 134
[10] // ANOTHER COMMENT
[11] ...
>>> header
'#HEADER3, THIRD SECTION\n'
</code></pre>
<p>第三部分保持未处理状态,因为其中没有行,但是如果有行,<code>header</code>变量已经在预期中设置好了。你知道吗</p>