python - 循环只迭代一次

标签 python

出于某种原因,尽管列表中有 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/

相关文章:

python - 使用Paramiko实现跳转主机(端口转发)时涉及的主机/IP地址和端口的说明

python - 查找列表中元素数量最少的所有无序分区

python - 网格索引和实际值之间的转换

python - 无法在 pypy3 中导入 numpy(使用 pip 可以正常安装)

Python 带条件断言

python - 将函数参数数据类型修复为 dataframe python

python - 在Python中打印所有匹配的JSON字典

python - 从 Excel 宏更新我的 wiki

python - 将 html 作为字符串循环一次

python - Flask 重定向数据