繁体   English   中英

python 计数器 function 不可散列类型:“列表”

[英]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 。 如果您将.appendre.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.

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