python:不可用的类型错误

l--*_*''' 16 python

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'
Run Code Online (Sandbox Code Playgroud)

我在这一行得到了上述错误:

data=medications_minimum3(data,[drug.upper()],1)
Run Code Online (Sandbox Code Playgroud)

(我也试过没有括号的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
Run Code Online (Sandbox Code Playgroud)

有谁知道我在做错了什么?

我知道我调用这个函数的方式肯定是错误的,因为我从不同的位置调用这个函数并且它工作正常:

d=medications_minimum3(c,drug_input,50)
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助!

Joh*_*ica 16

counter[row[11]]+=1
Run Code Online (Sandbox Code Playgroud)

你没有显示它是什么data,但显然当你循环它的行,结果row[11]是一个list.列表是可变对象,这意味着它们不能用作字典键.试图row[11]用作密钥会导致defaultdict抱怨它是一个可变的,即不可用的对象.

最简单的解决方法是row[11]从a 更改list为a tuple.通过做

counter[tuple(row[11])] += 1
Run Code Online (Sandbox Code Playgroud)

或者在data传递给调用者之前将其固定在调用者中medications_minimum3.一个元组只是一个不可变列表,所以它的行为与列表完全相同,只是一旦创建它就无法更改它.


Joh*_*ooy 7

我不认为转换为元组是正确的答案.你需要去看看你调用函数的位置并确保它c是一个字符串列表列表,或者你设计此函数的任何内容

例如,如果传递[c]给函数而不是传递给函数,则可能会出现此错误c