Traceback (most recent call last):
File "<pyshell#80>", line 1, in <module>
do_work()
File "C:\pythonwork\readthefile080410.py", line 14, in do_work
populate_frequency5(e,data)
File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5
data=medications_minimum3(data,[drug.upper()],1)
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
我在这一行收到上述错误:
data=medications_minimum3(data,[drug.upper()],1)
(我也试过不带括号的 drug.upper())
下面是这个函数的预览:
def medications_minimum3(c,drug_input,sample_cutoff): #return sample cut off for # medications/physician
d=[]
counter=collections.defaultdict(int)
for row in c:
counter[row[11]]+=1
for row in c:
if counter[row[11]]>=sample_cutoff:
d.append(row)
write_file(d,'/pythonwork/medications_minimum3.csv')
return d
有谁知道我在这里做错了什么?
我知道一定是错误的是我调用这个函数的方式,因为我从不同的位置调用这个函数并且它工作正常:
d=medications_minimum3(c,drug_input,50)
非常感谢您的帮助!
最佳答案
counter[row[11]]+=1
您没有显示 data
是什么,但显然当您遍历它的行时,row[11]
结果是一个 list
。列表是可变对象,这意味着它们不能用作字典键。尝试使用 row[11]
作为键会导致 defaultdict
提示它是一个可变的,即不可散列的对象。
最简单的修复方法是将 row[11]
从 list
更改为 tuple
。要么通过做
counter[tuple(row[11])] += 1
或者在 data
传递给 medications_minimum3
之前在调用者中修复它。元组只是一个不可变的列表,因此它的行为与列表完全一样,只是一旦创建就无法更改。
关于python:无法散列的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410206/