Python - 循环遍历嵌套循环打印项目,如果它改变

时间:2013-04-30 21:06:00

标签: python nested-loops

我循环遍历几个嵌套循环。我想打印第一个循环的项目,如果它改变。我怎么能这样做?

for slope in slopeList:
    for yarddist in yardDistList:
                      for chiptreesperacre in chipAcreList:
                          for chipvolpertree in chipVolList:
                              for smalllognumber in smallAcreList:
                                   for smalltreevolpertree in smallVolList:
                                       for largelogperacre in largeAcreList:
                                           for largetreevolpertree in largeVolList:
                                               data = [slope, yarddist, chiptreesperacre, chipvolpertree, smalllognumber, smalltreevolpertree, largelogperacre, largetreevolpertree]
                                               if slope changes:
                                                   print data

2 个答案:

答案 0 :(得分:3)

存储您之前看到的值,并进行比较:

previous_slope = None
for slope in as_many_loops_as_you_like:
    data = [slope, other_stuff]
    if slope != previous_slope:
        print data
        previous_slope = slope

答案 1 :(得分:0)

您可以将previous_slope添加到set并在内循环中添加后观察它的长度:

slope = set()
slope.add(previous_slope)
old_length = len(slope)
for first_loop:
   slope.add(current_slope)
   if len(slope) > old_length: 
     print 'Changed!'
     break

为每个内循环重复此模式。