gpt4 book ai didi

python - 循环只迭代一次

转载 作者:行者123 更新时间:2023-12-01 09:20:17 31 4
gpt4 key购买 nike

出于某种原因,尽管列表中有 2 个条目,以下代码块仅迭代 for 循环一次。

def remove_client(self, client):
try:
temp = client.followedby
for i in temp:
print("Begin")
print(i)
print(client.followedby)
i.unfollow_user()
print(client.followedby)
print("Passed")
print("Out of loop.")
except AttributeError:
print("AttributeError")
pass
self.cur_id[client.id] = False
self.clients.remove(client)

被调用的函数unfollow_user:

def unfollow_user(self):
self.send_host_message("Stopped following at {}.".format(time.asctime(time.localtime(time.time()))))
self.following.followedby.remove(self)
self.following = ""
print("end of unfollow user")

据我所知,这应该有效。它不会抛出任何错误,控制台输出为:

[<server.client_manager.ClientManager.Client object at 0x000001F87C2CCE80>, <server.client_manager.ClientManager.Client object at 0x000001F87C2CCD30>] Begin <server.client_manager.ClientManager.Client object at 0x000001F87C2CCE80> [<server.client_manager.ClientManager.Client object at 0x000001F87C2CCE80>, <server.client_manager.ClientManager.Client object at 0x000001F87C2CCD30>] end of unfollow user [<server.client_manager.ClientManager.Client object at 0x000001F87C2CCD30>] Passed Out of loop.

我在这里做错了什么?

最佳答案

简而言之,这是您正在做的事情的一个示例。

>>> x = [1,2]
>>> for i in x:
... x.remove(2)
... print("Hello world.")
...
Hello world.

当您在 python 中使用 for 循环构造时,您将在迭代器上调用 next()。当您在迭代时修改元素时,列表的内置迭代器的行为如下:

There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates.

您正在减少长度,迭代器会对此进行检查。因此它仅在 1 次迭代后就退出循环。

如果您想在所有元素上运行它,请执行复制并将其分配给您的临时文件:

import copy
temp = copy.copy(x)
for i in temp:
# Do whatever you want here

关于python - 循环只迭代一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50844987/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com