运行结果:

[2, 3, 4, 5, 6, 7, 8]
[2, 4, 5, 6, 7, 8]
[2, 4, 6, 7, 8]
[2, 4, 6, 7, 8]
[2, 4, 6, 7, 8]
二.问题分析

因为删除元素后,整个列表的元素会往前移动,而i却是在最初就已经确定了,是不断增大的,所以并不能得到想要的结果。

三.解决方法

1.遍历在新的列表操作,删除是在原来的列表操作


‘’’
a = [1,2,3,4,5,6,7,8]
print(id(a))
print(id(a[:]))
for i in a[:]:
if i > 5:
pass
else:
a.remove(i)
print(a)
print(‘-------------------------’)
print(id(a))

运行结果:

1836420141256
1836420222920
[2, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6, 7, 8]
[4, 5, 6, 7, 8]
[5, 6, 7, 8]
[6, 7, 8]

1836420141256

2.filter

内建函数filter()官方文档参考:https://docs.python.org/3/library/functions.html#filter

a = [1,2,3,4,5,6,7,8]
b = filter(lambda x: x>5,a)
print(list(b))

运行结果:

[6, 7, 8]

3.列表解析


‘’’
a = [1,2,3,4,5,6,7,8]
b = [i for i in a if i >5]
print(b)