【问题标题】:Python: List index out of range (Reversing a String)Python:列表索引超出范围(反转字符串)
【发布时间】:2018-06-07 05:10:25
【问题描述】:

我已阅读有关该主题的答案并弄清楚为什么会出现“列表索引超出范围”,但我似乎无法准确找到我必须做些什么来更正我的代码。我是初学者,因此可能忽略了正确的写作道德。

代码是反转已经提供的字符串,但我正在编写一种方式,以便我可以开始从用户那里获取未知数量的单词的输入,它仍然可以工作。

teststring = "this is a test"
result = []

result = teststring.split()     #holding individual element

final = []                      #to hold the reversed string
#print(result)
z = int(len(teststring) - 1)    #number of elements minus 1
#print(len(result))
count = 0
count = int(count)
#print(result[count])
for i in result:
    p = int(z - count)
    final[count] = result[p]
    print(final)
    count += 1
#print(count)
print(final)

我收到的错误是这样的

Traceback(最近一次调用最后一次): 文件“/home/pi/python/15_Reverse_String.py”,第 15 行,在 最终[计数] = 结果[p] IndexError: 列表索引超出范围

【问题讨论】:

  • 如果您只想反转列表,请执行此操作result[::-1]
  • 确实有效:D 谢谢。虽然只是出于好奇,但我想了解我的代码逻辑是如何失败的......
  • 变量final 为空,您可以通过这种方式填写列表。你甚至可以尝试这样做empty = [] final[2] = 4,你会得到同样的错误。请改用append
  • "".join(x for x in reversed(teststring))

标签: python-3.x


【解决方案1】:

您对 Python 中的列表的理解是错误的!我认为您将 Python 列表视为 C++ 数组。它们在某些概念上有所不同。 Python 中的列表是动态的。 append 方法在数组末尾添加一些内容。如果数组为空,添加一个元素,它成为第一个元素,第二个成为第二个元素,依此类推。

teststring = "this is a test"
result = []

result = teststring.split()     #holding individual element
lenght = len(result)
final = []                      #to hold the reversed string
#print(result)
for i in range(1,lenght+1):
    final.append(result[i*(-1)])
print(final)

在 Python 中,您可以使用索引 [-1] 访问 List 中的最后一个元素,您可以使用索引 [-2] 访问最后一个元素之前的元素,依此类推。我使用这种技术来反转列表。 例如在你的情况下:

result[-1] = test
result[-2] = a
.....

【讨论】:

  • 是的,我认为任何地方的数组都像 C++ 中的工作一样工作。那么,您的解决方案是否意味着使用 append 语句才能正常工作很重要?您能否在result[i*(-1)] 上指导我正确的方向?
【解决方案2】:

如果您只想反转一个列表,只需执行此结果[::-1]

【讨论】:

    【解决方案3】:

    您是否意识到z = int(len(teststring) - 1) 返回teststring 的大小?

    您将该数字用作访问result 数组的索引,该数组由teststring 变量的标记组成。

    这是您的代码的正确版本:

    teststring = "this is a test"
    result = []
    
    tokens = teststring.split()     #holding individual element
    
    final = []                      #to hold the reversed string
    
    for i in range(len(tokens) - 1, -1, -1):
        final.append(tokens[i])
    
    print(final)
    

    但最佳解决方案是:

    1. 使用tokens.reverse()函数。此函数反转您的数组。
    2. 使用tokens[::-1] 技巧。这个技巧会返回你的数组的反转,所以你需要保存到一个变量中。

    【讨论】:

    • for i in range(len(tokens) - 1, -1, -1): 在这部分中,len(token) -1 是 i 的第一个值,它是给定列表的最后一个索引,第二个 -1 代表 i 的最后一个值 ..最后一个 -1 表明范围是相反的方向。我说得对吗?
    猜你喜欢
    • 2016-02-10
    • 2019-12-24
    • 2021-07-23
    • 2021-10-22
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多