2012-10-05 122 views
0

我不断收到此错误:的Python:IndexError:列表索引超出范围

line 4, in timesTwo 
IndexError: list index out of range 

对这一计划:

def timesTwo(myList): 
counter = 0 
while (counter <= len(myList)): 
    if myList[counter] > 0: 
     myList[counter] = myList[counter]*2 
     counter = counter + 1 
    elif (myList[counter] < 0): 
     myList[counter] = myList[counter]*2 
     counter = counter + 1 
    else: 
     myList[counter] = "zero" 
return myList 

我不完全知道如何修正这个错误。有任何想法吗?

回答

2

您正在设置while循环的上限为myList的长度,这意味着计数器的最终值将是长度。由于列表索引从0开始,这会导致错误。您可以通过删除=标志修复:

while (counter < len(myList)): 

或者,你可以在一个for循环,可能有点好办了(不知道这是否符合您的使用情况下做到这一点,因此,上述应工作如果不是):

def timesTwo(myList): 

    for index, value in enumerate(myList): 
    if value is not 0: 
     myList[index] *= 2 
    else: 
     myList[index] = 'zero' 

    return myList 
+0

完美。谢谢我的男人 – user1707398

+0

@ user1707398没有概率,开心有帮助。 – RocketDonkey