num = [1,2,3,4,5,6]
for i in num:
if i % 2 !=0:
num.remove(i)
print("结果比较一:",num)
num1 = [1,2,3,4,5,7]
for j in num1:
if j % 2 !=0:
num1.remove(j)
print("结果比较二:",num1)
结果比较一: [2, 4, 6]
结果比较二: [2, 4, 7]
Process finished with exit code 0
从下标为0的第一个元素开始,数字为奇数,程序做删除动作;但是删除之后,由于我们操作的是原列表,删除1之后,后面的2,3,4,5,7下标会统一减一;程序会认为元素2的下标为0,程序会认为下标为0位置的元素已经遍历过,所以不对2进行判断,继续往下走。
num3 = [1,2,3,4,5,7]
for n in num3[::-1]: #利用列表当中的切片操作,逆向遍历
if n %2 !=0:
num3.remove(n)
print("结果比较三:",num3)
结果比较一: [2, 4, 6]
结果比较二: [2, 4, 7]
结果比较三: [2, 4]
Process finished with exit code 0
num4 = [1,2,3,4,5,7]
#使用列表推导式,直接把想要的数据提取出来
li = [li for li in num4 if (li%2==0)]
print("结果比较四:",li)
结果比较一: [2, 4, 6]
结果比较二: [2, 4, 7]
结果比较三: [2, 4]
结果比较四: [2, 4]
Process finished with exit code 0