在我的python代码中获取错误不可用类型列表

时间:2014-08-06 13:45:51

标签: python

当我运行我的python代码时出现此错误,但我有点学习python方式,而且我无法破译代码的错误。我得到了"不可用的类型:list"错误。错误显示在第54行和第35行。我想知道我是否错过了一些导入。我已经检查了代码,但我没有看到错误

#!/usr/bin/python

import string

def rotate(str, n):
    inverted = ''
    for i in str:
        #calculating starting point in ascii
        if i.isupper():
            start = ord('A')
        else:
            start = ord('a')
        d = ord(i) - start
        j = chr((d + n) % 26 + start)
        #calculating starting point in ascii(d + n) + start
        inverted += j

    return inverted


'''
    making a dictionary out of a file containing all words
'''
def make_dictionary():
    filename = "/home/jorge/words.txt"
    fin = open(filename, 'r')
    dic = dict()
    for line in fin:
    line = line.split()
    dic[line] = line
    return dic



'''
    function that rotates a word and find other words
'''
def find_word(word):
    rotated_words = dict() #dictionary for storing rotated words
    for i in range(1, 14):
    rotated = rotate(word, i)
    if rotated in dic:
        print word, rotated, i      



if __name__ == "__main__":

    words = make_dictionary()
    for w in words:
    find_word(w)

我想知道我是否错过了一些进口产品?

2 个答案:

答案 0 :(得分:3)

例如:

line = line.split()
dic[line] = line

linelist之后是split,并且正如错误消息所示,列表不可清除;字典键必须是可清除的。最小的修复是使用(不可变的,可散列的)tuple代替:

dic[tuple(line)] = line

请注意,词典可以是列表,该限制仅适用于

答案 1 :(得分:1)

这使line成为一个列表:

line = line.split()

dict密钥必须为hashable,且lists不可清除:

dic[line] = line

在你的代码中,你不清楚你需要一个字典。一组单词就足够了:

def make_set():
    filename = "/home/jorge/words.txt"
    result = set()
    with open(filename, 'r') as fin:
        for line in fin:
            for word in line.split():
                result.add(word)
    return result

使用集合将删除重复的单词。