python IndexError:list index out of range

t="你好苹果是我的"
import jieba
ls=jieba.lcut(t)
for i in range(len(ls):
if len(ls[i])<2:
del ls[i]
请教下,为什么 if len(ls[i])<2: 会index error

你顺着列表处理,删除后,导致了下标混乱。
如果要删除, 最好逆向处理。

t="你好苹果是我的"
import jieba
ls=jieba.lcut(t)

for i in range(len(ls)-1,-1,-1):
    if len(ls[i]) < 2:
        del ls[i]
print(ls)

在循环中删除列表元素时,因元素索引会改变,导致下标越界。解决办法是浅拷贝,用ls[:]或ls.copy()。

import jieba
t="你好苹果是我的"
ls=list(jieba.cut(t))
for x in ls.copy():
    if len(x)<2:
        ls.remove(x)
print(ls)

运行结果:

['你好', '苹果']

如有帮助,请点采纳。