使用切片的最后一次循环的Python循环中断

问题描述:

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

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) 

我想这是你想要什么:

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' 
+1

谢谢,我太亲近了。它总是小事情不是它。 ...走下去再读一遍。 – Michael 2014-09-30 22:10:26

你的切片是错误的。如果你想测试,如果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 

应该是:

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

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

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' 

一种方式做到这一点:

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

这里是与你有一般的想法不断的解决方案:

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'] 

这将评估为false。