英文:
.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
不要改变当前正在迭代的可迭代对象,通常会导致意外的结果,例如这种情况。在这种情况下,正在发生的情况是(不是确切的情况,但为了让你有个想法)
- 它看到" A "在 student -> 迭代器中的"下一个"是 "B"。
- 它从 student 中删除" A " -> 迭代器中的"下一个"是 "C"。
- 它移动到"下一个",它是 "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)
- It sees that "A" is in student ->The
next
in iterator is "B" - It removes "A" from student -> The
next
in iterator is "C" - 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论