`.remove()`在for循环中不按预期工作。

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

.remove() in for loop wasn't working as expected

问题

我刚开始学习如何编写代码。我尝试在for循环中使用remove()来删除特定值,如果条件满足,但结果不如我预期。

student = ["A", "B", "C"]
bad = input("who is absent?: ")
for i in student:
    if i in bad:
        student.remove(bad)
    else:
        print(i)

如果我在输入中输入A,结果看起来像这样:

who is absent?: A
C

我期望的输出应该是这样的:

who is absent?: A
B C
英文:

Just started to learn how to code.I was trying to use remove() in for loop to remove the specific value if condition met but the result is what I expected

student = ["A", "B", "C"]
bad = input("who is absent?: ")
for i in student:
    if i in bad:
        student.remove(bad)
    else:
        print(i)

The result looks like this if I typed A in input

who is absent?: A
C

I was expecting the out to be something like

who is absent?: A
B C

答案1

得分: 1

不要改变当前正在迭代的可迭代对象,通常会导致意外的结果,例如这种情况。在这种情况下,正在发生的情况是(不是确切的情况,但为了让你有个想法)

  1. 它看到" A "在 student -> 迭代器中的"下一个"是 "B"。
  2. 它从 student 中删除" A " -> 迭代器中的"下一个"是 "C"。
  3. 它移动到"下一个",它是 "C" 而不是 "B"。

如果你只需要打印剩下的部分,不要删除 "A"。
如果你确实需要删除项目,请参考这篇文章

英文:

As a general rule, don't change the iterable that you are currently iterating over. It can often lead to unintended outcomes such as this. In this instance, what is happening is (not exactly but to give you an idea)

  1. It sees that "A" is in student ->The next in iterator is "B"
  2. It removes "A" from student -> The next in iterator is "C"
  3. It moves to next, which is "C" instead of "B"

In the event that you only need to print the remaining ones, don't remove "A".
In the event that you do need to remove the items, refer to this post.

答案2

得分: 1

Remove方法会改变列表,所以每当你从列表中移除'A'时,在迭代过程中会导致问题,这就是为什么你看不到'B'。

通常情况下,你期望for i in student:像这样工作:
首先,i = 'A',然后i = 'B',然后i = 'C'
但是每当你从列表中移除'A'时,它会像这样工作:
i = 'A',然后它跳过B因为索引,然后i = 'C'。

因此,当你想要使用改变列表等函数时,你应该保留其副本并对其进行迭代。

student = ["A", "B", "C"]
student_copy = student.copy()
bad = input("who is absent?: ")
for i in student_copy:
    if i in bad:
        student.remove(bad)
    else:
        print(i)
英文:

Remove method mutates the list so whenever you remove 'A' from the list, while iterating it causes problems, thats why you dont see 'B'.

In normal you expect for i in student: to work like:
First, i = 'A', then i = 'B', then i ='C'
but whenever you remove 'A' from the list it works like:
i = 'A' then it skips B because of indexing then i = 'C'.

Therefore, when you want to use a function mutating a list or etc, you should keep a copy of it and iterate on it.

student = ["A", "B", "C"]
student_copy = student.copy()
bad = input("who is absent?: ")
for i in student_copy:
    if i in bad:
        student.remove(bad)
    else:
        print(i)

huangapple
  • 本文由 发表于 2023年3月9日 15:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681561.html
匿名

发表评论

匿名网友

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

确定