為什麼使用字典作為集合中的鍵會引發'TypeError: unhashable type: \'dict\'\”錯誤?

DDD
發布: 2024-10-27 00:36:03
原創
1005 人瀏覽過

Why does using a dictionary as a key in a set raise a

TypeError: Unhashable Type: 'dict'

問題:

為什麼以下程式碼會引發「類型」: unhableunhable. : 'dict'" 錯誤?

negfeats = [(word_feats(movie_reviews.words(fileids=[f])), 'neg') for f in negids]
stopset = set(stopwords.words('english'))

def stopword_filtered_word_feats(words):
    return dict([(word, True) for word in words if word not in stopset])

result=stopword_filtered_word_feats(negfeats)
登入後複製

答案:

發生錯誤是因為您嘗試使用字典作為創建的集合中的鍵通過 stopset 變數。但是,字典不是可哈希對象,這意味著它們不能用作集合或字典中的鍵。

解決方案:

要解決此問題,您可以將對凍結集合的否定功能中的字典是可散列的。以下程式碼顯示了修正後的版本:

negfeats = [(frozenset(word_feats(movie_reviews.words(fileids=[f])).items()), 'neg') for f in negids]
stopset = set(stopwords.words('english'))

def stopword_filtered_word_feats(words):
    return dict([(word, True) for word in words if word not in stopset])

result=stopword_filtered_word_feats(negfeats)
登入後複製

以上是為什麼使用字典作為集合中的鍵會引發'TypeError: unhashable type: \'dict\'\”錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!