사전을 세트의 키로 사용하면 \'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'

문제:

다음 코드에서 "TypeError: 해시할 수 없는 유형: '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의 사전을 해시 가능한 고정 세트로 변환합니다. 다음 코드는 수정된 버전을 보여줍니다.

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 학습자의 빠른 성장을 도와주세요!