我在Python中遇到了一个非常奇怪的行为。
使用从UserDict
派生的类,迭代器a.items()
在for循环中的行为与a.data.items()
不同,即使两者是相同的:
Python 3.3.1 (default, Apr 17 2013, 22:32:14)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datastruct import QueueDict
>>> a=QueueDict(maxsize=1700)
>>> for i in range(1000):
... a[str(i)]=1/(i+1)
...
>>> a.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992', 0.0010070493454179255), ('993', 0.001006036217303823), ('994', 0.0010050251256281408), ('995', 0.001004016064257028), ('996', 0.0010030090270812437), ('997', 0.001002004008016032), ('998', 0.001001001001001001), ('999', 0.001)]))
>>> a.data.items()
ItemsView(OrderedDict([('991', 0.0010080645161290322), ('992', 0.0010070493454179255), ('993', 0.001006036217303823), ('994', 0.0010050251256281408), ('995', 0.001004016064257028), ('996', 0.0010030090270812437), ('997', 0.001002004008016032), ('998', 0.001001001001001001), ('999', 0.001)]))
>>> a.items()==a.data.items()
True
>>> # nevertheless:
...
>>> for item in a.items(): print(item)
...
('992', 0.0010070493454179255)
>>> for item in a.data.items(): print(item)
...
('993', 0.001006036217303823)
('994', 0.0010050251256281408)
('995', 0.001004016064257028)
('996', 0.0010030090270812437)
('997', 0.001002004008016032)
('998', 0.001001001001001001)
('999', 0.001)
('991', 0.0010080645161290322)
('992', 0.0010070493454179255)
>>>
类定义如下:
import collections, sys
class QueueDict(collections.UserDict):
def __init__(self, maxsize=1*((2**10)**2), *args, **kwargs ):
self._maxsize=maxsize
super().__init__(*args, **kwargs)
self.data=collections.OrderedDict(self.data)
def __getitem__(self, key):
self.data.move_to_end(key)
return super().__getitem__(key)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._purge()
def _purge(self):
while sys.getsizeof(self.data) > self._maxsize:
self.data.popitem(last=False)
这很令人不安。你知道同一个对象[通过“视觉”检查,也通过(a.items()==a.data.items()) == True
]可以如何,以及为什么它在for循环中表现不同吗?你知道吗
谢谢你的帮助和想法!你知道吗
在迭代时更改集合可能会产生(在本例中是)一些意外的后果。你知道吗
你的干劲
…将当前键移到集合的结尾,这将使
a.items
上的for循环停止,因为它认为它已到达集合的结尾。你知道吗注释
move_to_end
行允许迭代按预期运行。你知道吗当您在
a.data.items
上迭代时,您的getter永远不会被调用,所以这不是问题。你知道吗相关问题 更多 >
编程相关推荐