2013-12-11 45 views

回答

0

如果i从0到len(a),那么i+1超出了索引的范围。

0
a=[1,2,3,4,5,6,'a','b','c'] 
print("list length: %d" % len(a)) 
for i in range(len(a)): 
if a[i]=='a': 
    print("swap a[%d] and a[%d]: " % (i+1, i)) 
    temp=a[i+1] 
    a[i+1]=a[i] 
    a[i]=temp 
    print(a) 

和出:

list length: 9 
swap a[7] and a[6]: 
[1, 2, 3, 4, 5, 6, 'b', 'a', 'c'] 
swap a[8] and a[7]: 
[1, 2, 3, 4, 5, 6, 'b', 'c', 'a'] 
swap a[9] and a[8]: 
Traceback (most recent call last): 
    File "so.py", line 6, in <module> 
    temp=a[i+1] 
IndexError: list index out of range 
+0

烨我理解了它在这里张贴后immedately ......我很抱歉问这么愚蠢的问题 – user3091069

+0

有我只是说“分手”声明出来for循环。谢谢! – user3091069

+0

@ user3091069 :),你可以接受答案。 – atupal