从Python列表中逐个迭代地删除一个项目。

huangapple go评论82阅读模式
英文:

Iteratively remove one item at a time from a Python list

问题

我觉得我不明白Python中的.remove()方法如何工作。

我有这个片段。b 变量的目的是在每次迭代中拥有一个不受影响的 a 列表的副本,但它并没有按照我期望的方式工作:

a = [0, 1, 2, 3, 4, 5]

for i in a:
    b = a.copy()
    a_i = b.remove(i)
    print(a_i)

我期望以下结果:

[1, 2, 3, 4, 5]
[0, 2, 3, 4, 5]
[0, 1, 3, 4, 5]
[0, 1, 2, 4, 5]
[0, 1, 2, 3, 5]
[0, 1, 2, 3, 4]

但实际上我得到了:

None
None
None
None
None

我的误解在哪里?

注意:我需要一个for循环格式的答案,因为这是我的代码的一部分的简化。

编辑:原始版本的代码片段中有一行 b = a,而不是 b = a.copy()。我已经纠正了它(谢谢),但我仍然得到一组 None 的数组。

英文:

I think I do not understand how the .remove() method works in Python.

I have this snippet. The point of the b variable is to have an untouched copy of the a list in every iteration, but it is not working as I expected:

a = [0, 1, 2, 3, 4, 5]

for i in a:
    b = a.copy()
    a_i = b.remove(i)
    print(a_i)

I would expect the following outcome:

[1, 2, 3, 4, 5]
[0, 2, 3, 4, 5]
[0, 1, 3, 4, 5]
[0, 1, 2, 4, 5]
[0, 1, 2, 3, 5]
[0, 1, 2, 3, 4]

And instead I get:

None
None
None
None
None

Where is my misconception?

NOTE: I need an answer in a for loop format because this is a simplification of a bigger part of my code.

EDIT: The original version of the snippet had a b = a line instead of b = a.copy(). I corrected that (thanks) but I am still getting an array of None's.

答案1

得分: 1

考虑这个答案:
https://stackoverflow.com/a/10665602/21445669

似乎问题是因为你在迭代过程中移除了元素。可能由于引用语义,将a赋值给b并不会创建一个独立的对象,这与你预期的不同。

尝试使用这个:
b = a.copy() 而不是 b = a

此外,.remove() 方法的返回值是 None!实际上,你希望在b.remove(i)之后的行中 print(b)

英文:

Consider this answer:
https://stackoverflow.com/a/10665602/21445669

Seems like the issue comes from removing elements of something you are iterating over. Probably assigning a to b doesn't create an independent object like you would expect due to reference semantics.

Try including this:
b = a.copy() instead of b = a.

Furthermore - the return value of the .remove() method is None! You actually want to print(b) in the line after b.remove(i)

huangapple
  • 本文由 发表于 2023年8月10日 18:59:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定