美文网首页
Python List 遍历remove错误

Python List 遍历remove错误

作者: Diolog | 来源:发表于2019-02-07 12:22 被阅读0次

在通常编程过程中,经常需要过滤List中的值,比如说:过滤列表中的负数。

现在有一个列表:

data = [-1, 10, -10, -7, -5, 0, -1, -5, -8, 6]

最初想法是:遍历列表并且移除负数,于是就写出如下代码:

for _ in data:
  if _ < 0:
    data.remove(_)

执行后的data为:

[10, -7, 0, -5, 6]

以上的代码方式无法获取当前数据在List中的真实索引,因此,
换一种方式组织代码:根据列表索引来执行的代码:

for _ in range(0,len(data)-1):
  if data[_]<0:
    data.pop(_)

执行结果:

-1
-10
-5
-1
-8
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>> data
[10, -7, 0, -5, 6]

可见执行结果完全一致,但是第二种方式报了错。

原因:
List在遍历的过程中,变量_存储的是最初的索引(删除之前的索引),但在遍历过程中,当第一个负数被删除之后,元素的实际索引已经发生变化(之后的元素的索引-1),这会导致被删除的元素后一位上的元素,被遗漏,即没有判断正负而被跳过。
这也是第二种方法导致IndexError的原因。

解决方法:
新建一个List,存储非负数。
代码如下:

data1 = list()
for _ in data:
  if _ >= 0:
    data1.append(_)

进阶:

data1 = [i for i in data if i>=0]

相关文章

  • Python List 遍历remove错误

    在通常编程过程中,经常需要过滤List中的值,比如说:过滤列表中的负数。 现在有一个列表: 最初想法是:遍历列表并...

  • Python中遍历 list 列表 remove 漏删

    title: Python中遍历 list 列表 remove 漏删date: 2017-11-04 23:46:...

  • python3 list遍历时删除

    问题:python3遍历list过程中通过list的remove删除列表元素后,将导致遍历元素不完整。 复现: 输...

  • Python List remove()

    remove() 函数用于移除列表中某个值的第一个匹配项。 以下代码实例展示了 remove()函数的用法: aL...

  • python 基础

    python 基础 tuple list append insert pop set add remove dic...

  • Linked List

    【1】链表删除 203. Remove Linked List Elements 解法一:遍历删除,需要新建一个d...

  • 039-什么是迭代

    在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历...

  • 9-1什么是迭代

    在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历...

  • 9、迭代

    在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历...

  • 46-什么是迭代

    在Python中,如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历...

网友评论

      本文标题:Python List 遍历remove错误

      本文链接:https://www.haomeiwen.com/subject/mdwwsqtx.html