[英]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.