python - 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
解决方案
首先检查反转列表的最佳方法。我认为您的反向实现可能不正确。有四 (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)))
推荐阅读
- javascript - 如何仅用一大块构建反应 js
- node.js - Socket.io 两次发出事件
- c - 将结构指针分配给另一个结构指针不起作用?
- azure-data-factory - 数据工厂数据流表达式与动态表达式
- bash - 设置新脚本的执行权限
- angular - 最终构建中存在哪些角度包
- ios - Xcode 未检测库..在范围内找不到 Firebase 'FaceDetectorOptions'
- terraform - 为什么在使用 terraform 自动缩放时缩放未创建的矩阵?
- firebase - 在 FirebaseFirestore 上为许多用户获取 postId
- php - 在php中显示数组中的第一张图片