这段代码给我一个错误unhashable type: dict,任何人都可以解释我的解决方案是什么
negids = movie_reviews.fileids('neg')
def word_feats(words):
return dict([(word, True) for word in words])
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)
Run Code Online (Sandbox Code Playgroud)
Lau*_*low 213
你正在尝试使用a dict作为另一个dict或一个的关键set.这不起作用,因为键必须是可清洗的.作为一般规则,只有不可变对象(字符串,整数,浮点数,frozensets,不可变元组)是可清除的(尽管例外是可能的).所以这不起作用:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
Run Code Online (Sandbox Code Playgroud)
要使用dict作为键,您需要将其转换为可能首先进行哈希处理的内容.如果您希望用作键的dict只包含不可变值,则可以像这样创建一个hashable表示:
>>> key = frozenset(dict_key.items())
Run Code Online (Sandbox Code Playgroud)
现在你可以key用作a dict或中的键set:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Run Code Online (Sandbox Code Playgroud)
当然,只要你想用dict查找某些东西,你就需要重复练习:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
Run Code Online (Sandbox Code Playgroud)
如果dict您希望用作键的值具有本身的值和/或列表,则需要递归"冻结"预期键.这是一个起点:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d
Run Code Online (Sandbox Code Playgroud)
小智 16
一个可能的解决方案可能是使用 JSON dumps() 方法,因此您可以将字典转换为字符串 ---
import json
a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]
set(c)
json.dumps(a) in c
Run Code Online (Sandbox Code Playgroud)
输出 -
set(['{"a": 10, "b": 20}'])
True
Run Code Online (Sandbox Code Playgroud)
这发生在我身上,因为我正在用 Typescript 思考,并尝试像这样设置一个 python 字典:
thing = { 'key': 'value' }
other_thing = {'other_key': 'other_value'}
my_dictionary = { thing, other_thing }
Run Code Online (Sandbox Code Playgroud)
然后我尝试:
my_dictionary = { thing: thing, other_thing: other_thing }
Run Code Online (Sandbox Code Playgroud)
...这仍然不起作用
最终起作用的是......
my_dictionary = { 'thing': thing, 'other_thing': other_thing }
Run Code Online (Sandbox Code Playgroud)
有趣的是,我们如何习惯不同语言的小语法技巧......
| 归档时间: |
|
| 查看次数: |
239471 次 |
| 最近记录: |