python - 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'
解决方案
Counter 中的所有对象都必须是可散列的:
Counter 是一个 dict 子类,用于计算可散列对象
该函数re.findall()
为您提供字符串列表。您可以像这样更新您的代码:
identifiers.extend(re.findall('[a-z]+|[0-9]+', element))
或者
identifiers += re.findall('[a-z]+|[0-9]+', element)
推荐阅读
- operating-system - 监视器:“在每个时间点,最多有一个线程可能正在执行它的任何方法。”
- python - Mongo 错过了捕获插入触发器
- python - 使用 spaCy nlp 分析 df 中的文档列的问题
- sql - SQL:显示孩子和兄弟/姐妹
- mongodb - MongoDB中的排序子项
- javascript - 如何从 chrome 扩展 api 获取返回值?
- angular8 - ng2-smart-table 中的 noDataMessage” 更改字体颜色并将 noDataMessage 对齐到中心
- c++ - c ++读取多维数组作为整数仅用于比较
- javascript - 为什么 do-while 不评估逻辑 &&?
- java - 如何在动态嵌套 json 响应中返回对象