栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何克服TypeError:无法散列的类型:“列表”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何克服TypeError:无法散列的类型:“列表”

如其他答案所示,错误是由于造成的

k = list[0:j]
,您的密钥被转换为列表。您可以尝试做的一件事是重新编写代码以利用该
split
功能:

# Using with ensures that the file is properly closed when you're donewith open('filename.txt', 'rb') as f:  d = {}  # Here we use readlines() to split the file into a list where each element is a line  for line in f.readlines():    # Now we split the file on `x`, since the part before the x will be    # the key and the part after the value    line = line.split('x')    # Take the line parts and strip out the spaces, assigning them to the variables    # once you get a bit more comfortable, this works as well:    # key, value = [x.strip() for x in line]     key = line[0].strip()    value = line[1].strip()    # Now we check if the dictionary contains the key; if so, append the new value,    # and if not, make a new list that contains the current value    # (For future reference, this is a great place for a defaultdict :)    if key in d:      d[key].append(value)    else:      d[key] = [value]print d# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

请注意,如果您使用的是Python 3.x,则必须稍作调整才能使其正常运行。如果使用打开文件

rb
,则需要使用
line =line.split(b'x')
(确保使用正确的字符串类型分割字节)。您也可以使用
with open('filename.txt', 'rU') asf:
(甚至
with open('filename.txt', 'r') as f:
)打开文件,它应该可以正常工作。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611814.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号