簡體   English   中英

在字典/ hashmap(在python中)中使用對象作為自己的鍵是否正常?

[英]Is it normal to use an object as its own key in a dictionary/hashmap (in python)?

假設我有一個我正在處理的傳入項目流。 對於每個項目,我提取一些數據並存儲它。 但很多項目都是一樣的。 我想跟蹤接收它們,但不能多次存儲相同的數據。 我可以像這樣實現它,但看起來很笨重:

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)

不幸的是。 實際上有點過分思考。 您需要做的就是使用集合

set對象是不同的可哈希對象的無序集合。 常見用途包括成員資格測試,從序列中刪除重復項,以及計算數學運算,如交集,並集,差異和對稱差異。

您的代碼可以替換為

item_record = set()
for .... :
   item_record.add(input_item)

更新雖然你說“,但不是多次存儲相同的數據”你的代碼實際上存儲多個項目。 在原始代碼中,無論項目緩存中是否存在項目,都將執行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問題 為什么不發布新問題並解釋您要解決的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM