我写了这段代码
phrase="dont't panic"
plist=list(phrase)
print(plist)
l=len(plist)
print (l)
for i in range(0,9):
plist.remove(plist[i])
print(plist)
输出
['d', 'o', 'n', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
12
Traceback (most recent call last):
File "C:/Users/hp/Desktop/python/panic.py", line 7, in <module>
plist.remove(plist[i])
IndexError: list index out of range
为什么在列表长度为12时显示:list index out of range
?
答案 0 :(得分:6)
您正在逐步浏览列表,删除字符:
遍历代码: I = 0
['o', 'n', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
I = 1
['o', 't', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
I = 2
['o', 't', 't', ' ', 'p', 'a', 'n', 'i', 'c']
I = 3
['o', 't', 't', 'p', 'a', 'n', 'i', 'c']
i = 4的
['o', 't', 't', 'p', 'n', 'i', 'c']
I = 5
['o', 't', 't', 'p', 'n', 'c']
I = 6
And now you're past the end of the array
我相信你打算删除前九个字符,但是一旦删除了第一个字符,它就不再是第一个字符了。因此,当您删除第二个字符时,实际上是删除了原始字符串的第三个字符,因此当您将其设置为i = 7或8时,数组中不再有足够的字符
更简单的&#34; pythonic&#34;做同样事情的方法是:
plist = plist[9:]