我运行了这个简单的代码:
mylist = [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}]
for item in mylist:
mylist.remove(item)
print('removed:', item, ', remains:', mylist)
我期待这个结果:
removed: {'a': 1} , remains: [{'b': 2}, {'c': 3}, {'d': 4}]
removed: {'b': 2} , remains: [{'c': 3}, {'d': 4}]
removed: {'c': 3} , remains: [{'d': 4}]
removed: {'d': 4} , remains: []
但我得到了这个结果:
removed: {'a': 1} , remains: [{'b': 2}, {'c': 3}, {'d': 4}]
removed: {'c': 3} , remains: [{'b': 2}, {'d': 4}]
你能解释一下这里发生了什么吗?为什么它没有像我预期的那样工作以及如何解决它?