按照索引在原列表上删除而不报错的方法
通常情况下,在原列表上删除元素会改变原列表的结构,遍历列表的时候会报越界
templist=[1,2,3,2,4,5,3,4,5,10,100,10,200,10]
for i in range(len(templist)):
if templist.count(templist[i])>1:
del templist[i]
print(templist)
结果:
Traceback (most recent call last):
File "E:/PYCHARM/test.u/test_script1.py", line 35, in <module>
if templist.count(templist[i])>1:
IndexError: list index out of range
使用元素遍历,在原列表中删除元素,不会报错
templist=[1,2,3,2,4,5,3,4,5,10,100,10,200,10]
#remove 移除,按值删除
for i in templist:
if templist.count(i)>1:
templist.remove(i)
print(templist)
若使用索引,则可以使用遍历值取列表切片的形式,这样原列表长度更改后,切片长度也会随之更改
#按索引删除
for i in range(len(templist[:])):
if templist.count(templist[i])>1:
del templist[i]
print(templist)
#按索引删除
for i in range(len(templist[:])):
if templist.count(templist[i])>1:
templist.pop(i)
print(templist)