首页 > 解决方案 > python 计数器函数不可散列类型:'list'

问题描述

我想在我的代码中使用 Counter 函数,但我得到了不可散列的类型错误。

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'

标签: python

解决方案


Counter 中的所有对象都必须是可散列的:

Counter 是一个 dict 子类,用于计算可散列对象

该函数re.findall()为您提供字符串列表。您可以像这样更新您的代码:

identifiers.extend(re.findall('[a-z]+|[0-9]+', element))

或者

identifiers += re.findall('[a-z]+|[0-9]+', element)

推荐阅读