我寫的這個 去除 字符串中多余空格,(所有空格處 只保留一個空格)的 方法
如果發生 remove 那么 len(l)的總大小就會減少,而 i的 最大值不變,所以會暴這個錯誤
def removeblank(line):
str=line.strip()
l=strtolist(str)
for i in range(len(l)):
if (l[i] == ' ' and i+1<len(l)):
a=l[i]
for j in range(i+1,len(l)):
b=l[j]
if l[j]==' ':
l.remove(l[j])
break
return l
用while的 方式就 不會報錯
list0=[0,1,2,3,4,5,6,7,8,9,10]
def listtest(list):
i=0
while i<len(list):
if i%3==0:
list.remove(i)
print(i)
i=i+1
listtest(list0)