python遍历数组的同时改动数组元素

python的for-loop的特殊性在于其更接近于「遍历」而非循环 Q:存在一个数组,对其进行遍历,符合条件的保留/删除,不符合条件的删除/保留,该如何操作? 错误示例: lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6] for item in lst: if item == 0: lst.remove(item) pri...

·
#python#列表#iterator

Table of Contents

python的for-loop的特殊性在于其更接近于「遍历」而非循环

Q:存在一个数组,对其进行遍历,符合条件的保留/删除,不符合条件的删除/保留,该如何操作?

错误示例:

lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]
 
for item in lst:
    if item == 0:
        lst.remove(item)
print lst
# 输出结果
# [1, 1, 2, 8, 3, 2, 5, 0, 2, 6]

方法一: 使用filter()函数

lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]
 
lst = filter(lambda x: x != 0, lst)
print lst

方法二:列表推导式

lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]
 
lst = [item for item in lst if item != 0]
print lst

方法三:遍历数组的拷贝,操作原始的数组

for item in lst[:]:
    if item == 0:
        lst.remove(item)
print lst

方法四:while循环 python的while与其他语言的while一致,都是纯粹的循环语句。

方法五:倒序遍历 正序遍历原数组可能出错的原因在于,遍历从前往后,对数组元素的修改(比如删除)将可能会导致改变未遍历到的元素的信息(比如下标)。 倒序遍历时修改元素不会影响到未遍历的元素(数组中靠前的元素)

for item in range(len(lst) - 1, -1, -1):
    if lst[item] == 0:
        del lst[item]
print lst
python遍历数组的同时改动数组元素 | 生活糖果