【问题标题】:Python for loop break on the last iteration using slicingPython for 循环在使用切片的最后一次迭代中中断
【发布时间】:2026-01-16 08:45:02
【问题描述】:

我正在尝试遍历一个列表并每次打印此列表,但仅在除最后一次迭代之外的所有迭代中打印“下一个”。我尝试了许多不同的想法,但运气不佳。下面是一个接近我想要的示例,但仍然打印“下一个”,因为我的 if 语句似乎没有中断。有没有办法像我尝试的那样使用切片来做我的比较语句?有没有更好的方法来解决这个问题?谢谢。

chapters = ['one', 'two', 'three',]

for x in chapters:
    print x
    if x == chapters[:-1]:
        break
    else:
        print 'next'

result:
one
next
two
next
three
next (<--I don't want this one)

【问题讨论】:

    标签: python for-loop slice


    【解决方案1】:

    我想这就是你想要的:

    chapters = ['one', 'two', 'three',]
    
    for x in chapters:
        print x
        if x != chapters[-1]:
            print 'next'
    

    或者你也可以这样做:

    for x in chapters:
        print x
        if x == chapters[-1]:
           break
        print 'next'
    

    【讨论】:

    • 谢谢你,我是如此接近。它总是小事不是吗。 ...走开再次阅读切片。
    【解决方案2】:

    您的切片错误。如果要测试x是不是最后一个元素,需要使用[-1]

    >>>chapters = ['one', 'two', 'three',]
    >>>for x in chapters:
    >>>    print x
    >>>    if x == chapters[-1]:
    >>>        break
    >>>    else:
    >>>        print 'next'
    one
    next
    two
    next
    three
    

    【讨论】:

      【解决方案3】:

      应该是:

      chapters = ['one', 'two', 'three']
      
      for x in chapters:
         print x
         if x == chapters[-1]:
            break
         else:
            print 'next'
      

      【讨论】:

        【解决方案4】:
        for x in chapters[:-1]:
            print x, '\nnext'
        print chapters[-1]
        

        或者你可以使用join:

        print '\nnext\n'.join(chapters)
        # '\nnext\n' is equal to '\n'+'next'+'\n'
        

        【讨论】:

          【解决方案5】:

          一种方法:

          chapters = ['one', 'two', 'three']
          length = len(chapters) - 1
          for i, x in enumerate(chapters):
              print x
              if i < length:
                  print 'next'
          

          【讨论】:

            【解决方案6】:

            这是一个符合您的总体想法的解决方案:

            chapters = ['one', 'two', 'three']
            
            for x in chapters:
                if x != chapters[-1]:
                    print x, '\nnext'
                else:
                    print x
            

            你切片的问题是你的切片,

            chapters[:-1]
            

            其实就是下面这个列表,

            ['one', 'two']
            

            并且您的代码正在将每个单独的章节值与此列表进行比较。所以,比较基本上是这样的:

            'one' == ['one', 'two']
            

            评估结果为假。

            【讨论】: