如果Python循环更改,则通过嵌套循环打印项目

2024-09-27 00:13:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在几个嵌套的循环中循环。如果第一个循环的项发生变化,我想打印它。我怎么能做到呢?在

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

Tags: infordataslopeslopelistsmalllognumberchipacrelistsmalltreevolpertree
2条回答

您可以将先前的斜率添加到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

对每个内循环重复此模式。在

存储您以前看到的值,并将其进行比较:

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

相关问题 更多 >

    热门问题