我已经阅读了有关该主题的答案,并找出了“列表索引超出范围”的原因,但我似乎无法找到我必须做的更正我的代码。我是初学者,因此可能忽略了正确的写作道德。
代码是反转已经提供的字符串,但我写的方式是这样我可以开始从用户输入未知数量的单词,它仍然有用。
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)
我收到的错误是
追踪(最近一次通话): 文件“/home/pi/python/15_Reverse_String.py”,第15行,in final [count] =结果[p] IndexError:列表索引超出范围
答案 0 :(得分:0)
您对Python中的列表的理解是错误的!我认为你认为Python列表就像C ++ Array一样。他们在一些概念上有所不同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
.....
答案 1 :(得分:0)
如果您只想反转列表,请执行此结果[:: - 1]
答案 2 :(得分:0)
您是否意识到{
date: "2016-07-18 00:00:00.000000",
timezone_type: 3,
timezone: "UTC"
}
会返回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)
功能。此功能可以反转您的阵列。tokens.reverse()
技巧。此技巧返回数组的反转,以便您需要保存到变量中。