使用for循环从列表中删除元素不起作用,但是使用列表理解是可以的 [英] Using for loop to remove elements from a list is not working, but using list comprehension is fine

查看:119
本文介绍了使用for循环从列表中删除元素不起作用,但是使用列表理解是可以的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这个问题实际上已经解决了,但是我仍然想知道为什么.我正在尝试从二维数组中删除元素,这是代码:

OK, this problem is actually solved, but I still want to know WHY. I am trying to remove elements from a 2-dimensional array, and here's the code:

print("adj in the while loop: ", adj)
for z in adj:
    print("for loop: ", z)
    if z[-1] is True:
        adj.remove(z)
result += 1
print("adj after all execution: ", adj)

控制台输出:

adj in the while loop: [[1, True], [0, 2, True], [1, True]]
for loop: [1, True]
for loop: [1, True]
adj after all execution: [[0, 2, True]]

这不符合预期.执行后正确的输出应为[].

This doesn't work as intended. The correct output after the execution should be [].

因此,我开始使用列表理解来编辑代码.

So I start to edit the code using list-comprehension.

列表理解代码:

adj = [z for z in adj if z[-1] is not True]

它按预期工作.输出为[].

It worked as intended. The output is [].

这使我感到困惑.为什么这两个看似相同的方法会产生不同的结果?有人可以向我解释吗?

This confuses me. Why would these two seemingly identical methods yield different results? Can anyone explain that to me?

推荐答案

这两种方法不相同.在列表理解中,您永远不会调用adj.remove(z).

These two methods are not identical. In the list comprehension, you never call adj.remove(z).

列表理解会在遍历adj的同时创建一个新列表,然后在完成后将该(空)列表分配回adj.迭代时它不会更改adj,仅在最后一次迭代之后.

The list comprehension is creating a new list as it iterates over adj, then you assign that (empty) list back to adj once it's done. It doesn't change adj while iterating, only after the last iteration.

这篇关于使用for循环从列表中删除元素不起作用,但是使用列表理解是可以的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆