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

Table of Contents

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

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

错误示例:

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

方法一: 使用filter()函数

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

方法二:列表推导式

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

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

1for item in lst[:]: 2 if item == 0: 3 lst.remove(item) 4print lst

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

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

1for item in range(len(lst) - 1, -1, -1): 2 if lst[item] == 0: 3 del lst[item] 4print lst
Mastodon