![](/img/trans.png)
[英]Python3: TypeError: unhashable type: 'list' when using Counter
[英]python counter function unhashable type: 'list'
我想在我的代碼中使用計數器 function,但我得到了不可散列的類型錯誤。
lexicalClass = file.readlines()
for lex in lexicalClass:
newList = re.findall('\S+', lex)
for element in newList:
if len(re.findall('[a-z]+|[0-9]+', element)):
identifiers.append(re.findall('[a-z]+|[0-9]+', element))
我在我的 txt 文件中放入了一些字符串,並將字符串放入“標識符”列表中。 現在,當我嘗試使用 print(Counter(identifiers)) 時,我得到了這個錯誤:
Traceback (most recent call last):
File "C:\Users\jule\.spyder-py3\temp.py", line 93, in <module>
print(Counter(identifiers))
File "C:\Users\jule\anaconda3\lib\collections\__init__.py", line 552, in __init__
self.update(iterable, **kwds)
File "C:\Users\jule\anaconda3\lib\collections\__init__.py", line 637, in update
_count_elements(self, iterable)
TypeError: unhashable type: 'list'
Counter 中的所有對象都需要是可散列的:
Counter 是一個 dict 子類,用於計算可散列對象
function re.findall()
為您提供字符串列表。 您可以像這樣更新您的代碼:
identifiers.extend(re.findall('[a-z]+|[0-9]+', element))
或者
identifiers += re.findall('[a-z]+|[0-9]+', element)
您可以在可哈希項目列表上使用計數器:
>>> Counter(['a','b','c','a'])
Counter({'a': 2, 'b': 1, 'c': 1})
您不能在不可散列的項目列表上使用計數器(並且列表是可變的,不可散列):
>>> Counter([['a','b'],['c','a']])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python@3.9/3.9.1_2/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py", line 593, in __init__
self.update(iterable, **kwds)
File "/usr/local/Cellar/python@3.9/3.9.1_2/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py", line 679, in update
_count_elements(self, iterable)
TypeError: unhashable type: 'list'
由於re.findall
生成元組列表或字符串列表,因此您需要直接在該列表上使用 Counter 。 如果您將.append
與re.findall
的列表結果一起使用,您最終會得到一個列表列表,您將看到您看到的錯誤。
幸運的是,您可以直接更新計數器。 您可以執行以下操作:
>>> txt='''\
... line 1
... Line 2
... LINE 3'''
>>> lines=Counter()
>>> lines.update(re.findall(r'^l', txt, flags=re.M))
>>> lines.update(re.findall(r'^L', txt, flags=re.M))
>>> lines.update(re.findall(r'^LINE', txt, flags=re.M))
>>> lines
Counter({'L': 2, 'l': 1, 'LINE': 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.