Python – 从嵌套循环只打印一次

我有一个excel文件,看起来像这样:

col1 col2 col3 col4 ----------------------------- row1 | 2,3,1 _ 1 w row2 | 3,2,7 _ 2 x row3 | _ _ 3 y row4 | 4,9 _ 4 z 

我在第2列写了一些值(使用XLWT),如下所示:

  col1 col2 col3 col4 ----------------------------- row1 | 2,3,1 x,y,w 1 w row2 | 3,2,7 y,x 2 x row3 | _ _ 3 y row4 | 4,9 z 4 z 

我的问题是,我的代码正确的地方迭代正确的值,但太多次(由于我想的嵌套循环)。

这是代码中最重要的部分(绒毛已被剪掉)。

 def question(): newtprint = set() #set I created outside of loops to call later one, supposed to prevent repeated iterations from nested loops for x in xrange(sheet.nrows): #iterates over all rows for i in xrange(len(newton)): #col1 for n in xrange(len(james)): #col2 if newton[i] == james[n]: newtprint.add(path[n]) #adds specified col4 value into set print newtprint, x #writes current set being written and row it's written into sheety.write(x, 1, str(newtprint)) #writes into col2 based on col4 sets wb.save('C:/.../names.xls') 

我早些时候对此有所帮助,而且我认为它是有效的,但是我想它并不像我最初所想的那样工作: 处理Python中的嵌套循环 – 选项?

只是寻找选项,以防止不断迭代。 以下是我的cmd中出现的内容: http://i.imgur.com/VFkDVxw.png

红色方括号显示正常打印的第一组值,然后在转到下一组值并重复打印之前,在一小段时间内一次又一次地开始打印相同的值。

这会更有意义:

 def question(): for x in xrange(sheet.nrows): #iterates over all rows newtprint = set() for i in xrange(len(newton)): #col1 for n in xrange(len(james)): #col2 if newton[i] == james[n]: newtprint.add(path[n]) #adds specified col4 value into set print newtprint, x #writes current set being written and row it's written into sheety.write(x, 1, str(newtprint)) #writes into col2 based on col4 sets wb.save('C:/.../names.xls') 

您将每行的newtprint写入新文件。 因此,你应该为每一行都做一个新的设置。