繁体   English   中英

python:不可散列的类型错误

[英]python: unhashable type error

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 元组只是一个不可变的列表,因此它的行为与列表完全一样,只是一旦创建就无法更改。

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

例如,如果您将[c]传递给函数而不是c您可能会收到此错误

正如drug.upper()在评论中所说,没有明显的理由让你从drug.upper()创建一个单元素列表(这意味着药物是一个字符串)。

但这不是您的错误,因为您的函数medications_minimum3()甚至不使用第二个参数(您应该解决的问题)。

TypeError: unhashable type: 'list'通常意味着您试图将列表用作哈希参数(例如访问字典)。 我会在counter[row[11]]+=1查找错误——你确定row[11]是正确的类型吗? 在我看来,这可能是一个列表。

  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 ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM