为了账号安全,请及时绑定邮箱和手机立即绑定

Python 字典和列表比较

Python 字典和列表比较

饮歌长啸 2021-07-21 13:14:04
我试图将列表“行”中的每个项目与字典“dic”进行比较,然后将行中的项目添加到 dic(如果它不存在),或者将 1 添加到字典中的键值。import stringdef uniques():    file = open("test.txt", "r")    dic = {}    data = file.read().replace('\n', ' ')    strip = removePunctuation(data)    lines = strip.split(' ')    print(strip)    print(lines)    for item in lines:        #this produces an error of unhashable type: 'list'        if lines in dic:            dic[item] = dic[item] + 1        else:            print("else ran")            dic[item] = 1    for item in dic:        print(item, dic[item])        print("There are " + str(len(dic)) + " items in the dictionary")def removePunctuation(text):    text = text.strip()    return text.rstrip(string.punctuation)uniques()
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

它的

if item in dic:
      dic[item] = dic[item] + 1

代替

if lines in dic:
      dic[item] = dic[item] + 1


查看完整回答
反对 回复 2021-07-28
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

if item in dic.values():

代替 if lines in dic:

这将创建一个 dict_value 列表。


查看完整回答
反对 回复 2021-07-28
  • 2 回答
  • 0 关注
  • 311 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号