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)
非常感谢你的帮助!
答案 0 :(得分:16)
counter[row[11]]+=1
您没有显示data
是什么,但显然当您遍历其行时,row[11]
结果是list
。列表是可变对象,这意味着它们不能用作字典键。尝试使用row[11]
作为密钥会导致defaultdict
抱怨它是一个可变的,即不可用的对象。
最简单的解决方法是将row[11]
从list
更改为tuple
。通过做
counter[tuple(row[11])] += 1
或在data
传递给medications_minimum3
之前将其固定在来电者中。一个元组只是一个不可变列表,所以它的行为与列表完全相同,只是一旦创建它就无法更改它。
答案 1 :(得分:7)
我不认为转换为元组是正确的答案。你需要去看看你调用函数的位置,并确保c
是一个字符串列表列表,或者你设计这个函数的任何东西
例如,如果您将[c]
传递给函数而不是c
答案 2 :(得分:3)
正如吉姆·加里森在评论中所说,没有明显的理由说明你为drug.upper()
制作一个单元素列表(这意味着药物是一个字符串)。
但这不是你的错误,因为你的函数medications_minimum3()
甚至没有使用第二个参数(你应该修复的东西)。
TypeError: unhashable type: 'list'
通常意味着您尝试使用列表作为哈希参数(比如访问字典)。我会在counter[row[11]]+=1
中查找错误 - 您确定row[11]
的类型正确吗?听起来我可能是一个清单。
答案 3 :(得分:0)
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
不可取消。这是一个清单。这正是(并且只是)错误消息的含义。您可能不喜欢它,但这是错误消息。
这样做
counter[tuple(row[11])]+=1
另外,简化。
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]