有没有办法改变for循环的迭代器?

时间:2019-05-16 16:27:10

标签: python for-loop

我正在for循环中读取每行的文件行,并执行while循环,以修改像下面这样的迭代器循环:

for line in archive:
    ...
    if re.search("{",line):
        while not re.search("}",line):
          ...
          line = next_line
    ...

下面的完整代码

import re

a = ["{\n","int b,c,d\n","#pragma omp parallel for\n","for (int i=0;i<10;i++)\n",'1\n','2\n','3\n','\n4',"}\n",'6','7','8','9','0','z','y']
listwh=[]
a_it=iter(a)
text =[]
flagcb=0
for j in a:
  print(j)
for line in a_it:  
  if re.search("{",line):

     flagcb=flagcb+line.count("{")-line.count("}")
     while(flagcb>0):
         listwh.append(line)
         print(flagcb)
         print(line)
         flagcb=flagcb+line.count("{")-line.count("}")
         line = next(a_it)
  text.append(line)  

for i in listwh:
  print(i)
print("\ninterval\n")
#for i in text:
#  print(i)

我想一直停留在while循环中,直到停止读取档案的终止条件为止。

1 个答案:

答案 0 :(得分:1)

您可以从可迭代对象显式创建一个迭代器:

archive_iter = iter(archive)

然后它将在循环之间保持高级状态。

for line in archive_iter:
    if '{' in line:
        while '}' not in line:
            line = next(archive_iter)