【问题标题】:python keeps returning typeerror: unhashable type: listpython 不断返回 typeerror: unhashable type: list
【发布时间】:2018-06-04 09:07:31
【问题描述】:

我不擅长编程,只是为了好玩和在线获取代码示例。所以我决定我想做以下事情:

  1. 统计总字数
  2. 计算“whereby”字数
  3. 除以总字数的'whereby'计数

但是,我不断收到“不可散列的类型:“列表”。我认为这是因为我使用了 frequency_list 但我不明白我该怎么做。

错误回溯: 回溯(最近一次通话最后): 文件“C:\Users\user\AppData\Local\Programs\Python\Python36-32\whereby.py”,第 31 行,在 打印(整数(频率[字数])/字数) TypeError: unhashable type: 'list'

import re
import string

frequency = {}
wherebyity = {}
document_text = open('C:/Users/user/desktop/text.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall('whereby', text_string)

for word in match_pattern:
    count = frequency.get(word, 0)
    frequency[word] = count + 1

frequency_list = frequency.keys()

for words in frequency_list:
    print (words, frequency[words])
    print (type(frequency))
    print (type(frequency[words]))
    print (frequency)

with open('C:/Users/user/desktop/text.txt', 'r') as f:
    p = f.read() # p contains contents of entire file
    # logic to compute word counts follows here...
    words = p.split()
    wordCount = len(words)
    print ("The total word count is:", wordCount)
    print (type(wordCount))


    print(int(frequency[words])/wordCount)

【问题讨论】:

  • 我们能看到错误痕迹吗?
  • Traceback(最近一次调用最后):文件“C:\Users\user\AppData\Local\Programs\Python\Python36-32\whereby.py”,第 31 行,在 中打印(int(frequency[words])/wordCount) TypeError: unhashable type: 'list'
  • 我怀疑 'words' 是一个列表,而不是关键字 - 您不能将列表用作 dict 关键字。在调试器中检查 'words' 并验证它是否是您所需要的。

标签: python


【解决方案1】:

在您的words = p.split() 行中,您将words 设置为list 拆分对象。

您的错误是说您无法在最后一行的frequency 中获取words 索引处的项目,因为无法对lists 进行哈希处理。你可以阅读更多关于 Python 字典的工作原理以及为什么他们使用散列here

我认为您的意思是在最后一行中添加其他内容而不是 words,也许是 'whereby'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-11
    • 2020-05-11
    • 2022-12-05
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2020-03-27
    相关资源
    最近更新 更多