【问题标题】:Why am i getting a unhashable type error为什么我得到一个不可散列的类型错误
【发布时间】:2015-07-05 07:50:51
【问题描述】:

我正在尝试从两个输入文件中查找所有匹配的单词,但我不断收到“TypeError: unhashable type: 'list'”。我不知道为什么。有人可以告诉我我做错了什么以及如何解决它

#!/usr/bin/python3

#First file
file = raw_input("Please enter the name of the first file: ")

store = open(file)

new = store.read()

#Second file
file2 = raw_input("Please enter the name of the second file: ")

store2 = open(file2)

new = store2.read()

words = set(line.strip() for line in new)

for line in new:
    word2 = line.split()
    if word2 in words:
            print words

【问题讨论】:

    标签: python input split store words


    【解决方案1】:

    您收到TypeError: unhashable type: 'list' 异常,因为word2 = line.split() 正在返回一个列表对象。 您正在尝试在 words 设置对象中搜索列表(不可散列的对象)。

    例如:

    >>> word2 = 'abc'
    >>>
    >>> word2.split() in set(['abc', 'def'])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'
    

    split 在这里不是正确的函数。您应该使用strip 函数来删除whitespaces

    >>> word2.strip() in set(['abc', 'def'])
    True
    

    【讨论】:

    • 当我这样做时,我得到了所有匹配的字母。我需要所有匹配的单词
    • 你能添加一个你所面临的例子吗?
    • 我得到了一堆像这样的行 "set(['', '"', ',', '.', '?', 'A', 'I', 'M ','W','a','c','b','e','d','g','f','i','h','k','m', 'l'、'o'、'n'、'p'、's'、'r'、'u'、't'、'w'、'v'、'y'])"
    • 我需要它来返回所有匹配的单词,例如“apple”“away”等
    • 这是因为words = set(line.strip() for line in new)。在这里,您的 new 对象正在向您返回整个文件内容,并且当您迭代它时,它正在迭代每个字符。您应该逐行迭代它并按空格拆分它们并将其附加到某个列表中。最后调用该列表中的set 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-24
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多