首页 > 解决方案 > IndexError:反转列表时列表索引超出范围错误

问题描述

当我输入这个:

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

标签: pythonpython-3.x

解决方案


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

推荐阅读