IndexError:反转列表时列表索引超出范围错误

时间:2019-02-09 14:49:37

标签: python python-3.x

当我键入此内容时:

// Make sure the client is loaded and sign-in is complete before calling 
gapi.client.drive.files.create({
    "resource": {}
  })
  .then(function(response) {
    // Handle the results here (response.result has the parsed body).
    console.log("Response", response);
    },
    function(err) { 
      // handle error here.
      console.error("Execute error", err); });
  }

我收到此错误

def FirstReverse(str): 

 # code goes here

x = len(str)

s = list(str)

while x >= 0:
 print s[x]
 x = x - 1

# keep this function call here  
# to see how to enter arguments in Python scroll down
print FirstReverse(raw_input())

3 个答案:

答案 0 :(得分:1)

实际上得到了, 答案就在这里!

>> x = list(‘1234’)

>> x

[‘1’ , ‘2’ , ‘3’, ‘4’]

>> length = len(x)

4

>> x[length]
  

索引错误:列表索引超出范围   注意:列表索引从零(0)开始。

但是这里的长度是四个。

上面列表的分配是这样的:

x[0] = 1

x[1] = 2

x[2] = 3

x[3] = 4

x[4] = ?

如果您尝试访问x [4](无或为空),则列表索引将超出范围。

答案 1 :(得分:1)

Python索引从0开始。因此,对于字符串“ Hello”,索引0指向“ H”,索引4指向“ o”。当您这样做时:

x = len(str)

您将x设置为5,而不是最大索引4。因此,请尝试以下操作:

x = len(str) - 1

另外,另一个指针。而不是:

x = x - 1

您可以简单地输入:

x -= 1

答案 2 :(得分:1)

首先检查逆向列表的最佳方法。我认为您的逆向实现可能不正确。有四种(4)可能的方法可以反转列表。

my_list = [1, 2, 3, 4, 5]

# Solution 1: simple slicing technique..
print(my_list[::-1]) 

# Solution 2: use magic method __getitem__ and 'slice' operator
print(my_list.__getitem__(slice(None, None, -1))) 

# Solution 3: use built-in list.reverse() method. Beware this will also modify the original sort order
print(my_list.reverse())

# Solution 4: use the reversed() iteration function
print(list(reversed(my_list)))