仅循环迭代

2024-05-20 13:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,下面的代码块只迭代For循环一次,尽管列表中有2个条目。在

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

^{pr2}$

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

[<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.

我做错什么了,这里?在


Tags: ofselfclientobjectservermanagertempremove
1条回答
网友
1楼 · 发布于 2024-05-20 13:17:35

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

>>> 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.

您正在减少长度,迭代器会检查它。所以它只在一次迭代后就退出循环。

如果要在所有元素中运行它,请执行复制并将其分配给temp:

^{pr2}$

相关问题 更多 >