假设我有一个输入的项目流,我正在处理。对于每一项,我提取一些数据并存储它。但是很多东西都是一样的。我想要跟踪接收到的数据,但不要多次存储相同的数据。我可以这样实现它,但它似乎很笨重:
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)发布于 2017-01-23 04:42:56
很不幸是的。其实是想得太多了。您需要做的就是使用集合
set对象是不同的可哈斯对象的无序集合。常见的用途包括成员资格测试、从序列中删除重复项以及计算数学运算(如交、并、差和对称差)。
您的代码可以用
item_record = set()
for .... :
   item_record.add(input_item)update虽然您说了",但不存储相同的数据不止一次“您的代码实际上存储了多个项。在原始代码中,无论项缓存中是否存在项,都将执行item_record.append()调用
try:
    item_record.append(item_cache[item])
except KeyError:
    item_cache[item] = item  # this is the part that seems weird
    item_record.append(item)所以名单上会有重复的。但是,我不太确定您是否在追加正确的对象,因为您还没有共享Item类的代码。我相信我们真正拥有的是一个xy问题。为什么不发布一个新的问题并解释一下你想要解决的问题。
https://stackoverflow.com/questions/41799309
复制相似问题