2014-09-30 30 views
0

我試圖循環遍歷列表並每次都打印此列表,但只在最後一次迭代中打印「下一個」。我嘗試了許多不同的想法,但沒有多少運氣。下面是一個接近我想要的例子,但仍然打印'下一個',因爲我的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) 

回答

0

我想這是你想要什麼:

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

0

你的切片是錯誤的。如果你想測試,如果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 
0

應該是:

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

for x in chapters: 
    print x 
    if x == chapters[-1]: 
     break 
    else: 
     print 'next' 
0
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' 
0

一種方式做到這一點:

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

這裏是與你有一般的想法不斷的解決方案:

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。