【发布时间】:2017-06-07 13:08:04
【问题描述】:
假设我有一个正在处理的传入项目流。对于每个项目,我都会提取一些数据并将其存储。但是很多东西都是一样的。我想跟踪接收它们,但不要多次存储相同的数据。我可以这样实现,但看起来很笨重:
item_cache = {}
item_record = []
def process(input_item):
item = Item(input_item) # implements __hash__
try:
item_record.append(item_cache[item])
except KeyError:
item_cache[item] = item # this is the part that seems weird
item_record.append(item)
我只是想多了?在 python 中做d[thing] = thing 是一个相当正常的构造吗?
编辑
回应下面的评论。这是更完整的示例,展示了此代码如何避免存储输入数据的重复副本。
class Item(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __eq__(self, other):
return self.a == other.a and self.b == other.b and self.c == other.c
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash((self.a, self.b, self.c))
def __repr__(self):
return '(%s, %s, %s)' % (self.a, self.b, self.c)
item_cache = {}
item_record = []
def process_item(new_item):
item = Item(*new_item)
try:
item_record.append(item_cache[item])
except KeyError:
item_cache[item] = item
item_record.append(item)
del item # this happens anyway, just adding for clarity.
for item in ((1, 2, 3), (2, 3, 4), (1, 2, 3), (2, 3, 4)):
process_item(item)
print([id(item) for item in item_record])
print(item_record)
【问题讨论】:
-
如果
thing是不可变的(它必须是,否则你不能将它用作键),也许set()是一个更好的缓存容器? -
断章取意,使用 Object 的某些属性作为键
item.some_unique_id(可能是其他属性的元组/组合)会更好吗?
标签: python dictionary hashmap hashtable