不可用的类型:' list' Python中的错误

时间:2016-01-18 06:25:18

标签: python python-3.x

我已经在stackoverflow中检查了与不可用类型:' list' 相关的一些问题答案,但它们都没有帮助我。这是我的部分代码:

keyvalue = {};
input_list_new = input_list;

for file in os.listdir('Directory/'):
    pathname = os.path.join('Directory/', file)
    dict_table = []; # creates blank 2d array
    with open(pathname) as dict_file:
        for line in dict_file:
            dict_table.append(line.strip().split("\t"))
    dict_list = [];
    for i in list(range(0, len(dict_table))):
        dict_list.append(dict_table[i][0])
    matched = list(set(dict_list) & set(input_list)) 
    for i in list(range(0, len(matched))):
        temp = [dict_table[0][0]] + dict_table[(dict_list.index(matched[i]))]

        input_list_new.insert((input_list_new.index(matched[i])), temp)

        dict = {matched[i] : temp}
        keyvalue.update(dict)

其中dict_table是列表,dict_list只是一个列表& keyvalue是一个python字典。当我对该行input_list_new.insert((input_list_new.index(matched[i])), temp)发表评论时,整个代码运行良好,但如果没有对该行进行评论,则会显示Unhashable type : 'list'错误。

2 个答案:

答案 0 :(得分:1)

错误消息与行

不对应
input_list_new.insert((input_list_new.index(matched[i])), temp)

被评论出来。如果有的话,罪魁祸首是行

dict = {matched[i] : temp}

问题应该是您尝试使用列表作为词典键。这是一个简单可重复的问题:

{[]: 5}  # throws TypeError: unhashable type: 'list'

失败的原因是因为字典也被称为 hashmap (在其他语言中)。密钥必须是可清除的,并且在Python中尝试使用列表作为密钥会引发错误,因为列表不可清除(请参阅“hashable”条目here)。

避免使用列表,因为字典键可以解决问题。

答案 1 :(得分:1)

这是我的猜测......您提到错误与行matched = list(set(dict_list) & set(input_list))有关。这可能是因为在input_listdict_list中,您有列表中的列表....集合中的项目需要可散列,因此不可变..例如,你不能做set([1,5,6,[1,3]]) ...这将给出不可用的类型列表错误...但你可以执行set([1,5,6,(1,3)])因为元组是不可变的并且可以删除