像python中的函数一样推回?

时间:2010-11-14 03:13:59

标签: python

对不起伙计们!对不起。我是Python的初学者。我正在编写以下代码:

for line in file:
 if StartingMarker in line:
  # Here: I want to push back 'line' back in 'file'
    for nextline in file:
     if EndingMarker in line:
        # Do some Operation
print "Done"

如何将'line'推回'file'?

先谢谢。

4 个答案:

答案 0 :(得分:5)

不要退缩,屈服。

def starttoend(it):
  for line in it:
    if 'START' in line:
      yield line
      break
  for line in it:
    yield line
    if 'END' in line:
      break

l = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']

i = iter(l)
for line in starttoend(i):
  print line

如果需要更多序列,请再次使用迭代器。

答案 1 :(得分:1)

我知道没有迭代器你可以开始迭代,然后推送一个已被带回迭代器的项目。但是你可以做的是创建一个新的迭代器(带有itertools.chain),迭代当前项和原始迭代器中的其余项。类似的东西:

import itertools

with open('some-input-file') as f:
    it = iter(f)
    for line in it:
        if StartingMarker in line:
            it2 = itertools.chain(iter([line]), it)
            for nextline in it2:
                if EndingMarker in nextline:
                    # Do some Operation

答案 2 :(得分:0)

for line in file:
    if StartingMarker in line and EndingMarker in line:
        # look ma! no need to push back

编辑:

for line in file:
    if StartingMarker in line:
        # do some operation
        if EndingMarker in line:
            # do some other operation

答案 3 :(得分:0)

for line in file:
    if StartingMarker in line:
        if endingmarker in line:
            #do operation
        else:
            for nextline in file:
                if EndingMarker in line:
                     # Do some Operation
print "Done"