Python - 仅从嵌套循环中打印一次

时间:2015-12-01 16:38:08

标签: python excel nested-loops xlwt

我有一个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')

我之前有过这方面的帮助,我觉得它有用,但我猜它没有像我原先认为的那样起作用:Dealing with Nested Loops in Python - Options?

只是寻找防止持续迭代的选项。这是我的cmd中显示的内容:http://i.imgur.com/VFkDVxw.png

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

1 个答案:

答案 0 :(得分:1)

这会更有意义:

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到新文件中。因此,您应该为每一行创建一个新集。

相关问题