【问题标题】:IndexError: list index out of range error when reversing a list [duplicate]IndexError:反转列表时列表索引超出范围错误[重复]
【发布时间】:2019-07-03 13:51:28
【问题描述】:

当我输入这个时:

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())

我收到此错误

ERROR ::--Traceback (most recent call last):
File "/tmp/105472245/main.py", line 14, in <module>
print FirstReverse("Argument goes here")
File "/tmp/105472245/main.py", line 7, in FirstReverse
print s[x] IndexError: list index out of range

【问题讨论】:

  • 如果一个字符串是x = list("hello"),它的长度是5,但是由于python索引是从0开始的,所以没有元素x[5]。最后一个元素是x[4]。所以试试x = len(str) - 1
  • x = len(str) - 1
  • 为什么要让它变得复杂? str[::-1] 可以。另外,不要将您的字符串命名为str

标签: python python-3.x


【解决方案1】:

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

x = len(str)

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

x = len(str) - 1

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

x = x - 1

你可以简单地说:

x -= 1

【讨论】:

    【解决方案2】:

    其实明白了 这就是答案!

    >> 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] = ?
    

    如果您尝试访问为 None 或 Empty 的 x[4],则会出现超出范围的列表索引。

    【讨论】:

      【解决方案3】:

      首先检查反转列表的最佳方法。我认为您的反向实施可能不正确。有四 (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)))
      

      【讨论】:

      • 方法2对于初学者来说可能太多了。此外,我们已经确定了为什么 OP 的反向方法不起作用。
      • 方法1、3、4对于初学者来说已经足够了。只是个人喜好。但要注意方法3也会修改位置参数的顺序。
      猜你喜欢
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2012-03-21
      • 2019-09-22
      • 2017-07-02
      • 2018-04-22
      相关资源
      最近更新 更多