鱼C论坛

 找回密码
 立即注册
查看: 2094|回复: 4

[已解决]关于TypeError: unhashable type: 'list'的问题

[复制链接]
发表于 2020-8-13 23:52:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
新手求教:
test_one={
   'aa':'11',
   'bb':'22',
   'cc':'33',
   'dd':'44',
   'ee':'55'
   }
test_two=['bb','dd']
for name in test_one.keys() :
   print (name.title())
   
   if test_two in test_one :
      print (name + one[name])
为什么会出现:
Aa
Traceback (most recent call last):
  File "E:\python库\no2.py", line 12, in <module>
    if test_two in test_one :
TypeError: unhashable type: 'list'
的报错,怎么解决,求大神指点
最佳答案
2020-8-14 07:08:53
你应该是想这样吧:
test_one = {
    'aa': '11',
    'bb': '22',
    'cc': '33',
    'dd': '44',
    'ee': '55'
}
test_two = ['bb', 'dd']
for name in test_one.keys():
    print(name.title())

    if 'bb' in test_one or 'dd' in test_one:
        print(name + test_one[name])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-8-14 02:05:15 | 显示全部楼层
本帖最后由 全能小乌贼 于 2020-8-14 02:06 编辑

你的for name in test_one.keys() :命令,五次循环,name会取五个值"aa","bb",'cc','dd',‘ee’, 然后name.title()会大写字符串的第一个首字母,所以第一次循环会输出"Aa",但是因为你的if test_two in test_one :命令错误,所以代码不会往下运行了,所以只会输出"Aa",如果你将 if test_two in test_one :和print (name + one[name])删除或者注释掉,就会得到Aa,Bb,Cc,Dd,Ee。至于if test_two in test_one :错误的原因是因为你的test_two 是一个list类型,而 test_one是一个字典类型,是不可能满足包含关系的,所以if判断不成立,从而报错。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-14 07:08:53 | 显示全部楼层    本楼为最佳答案   
你应该是想这样吧:
test_one = {
    'aa': '11',
    'bb': '22',
    'cc': '33',
    'dd': '44',
    'ee': '55'
}
test_two = ['bb', 'dd']
for name in test_one.keys():
    print(name.title())

    if 'bb' in test_one or 'dd' in test_one:
        print(name + test_one[name])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-14 10:34:05 | 显示全部楼层
本帖最后由 求资专用 于 2020-8-14 10:48 编辑

列表和字典这些可变的对象是不可哈希对象,所以不能这样进行判断,解决方法是将这个列表变成可哈希的元组。
test_one = {
    'aa': '11',
    'bb': '22',
    'cc': '33',
    'dd': '44',
    'ee': '55'
}
test_two = ['bb', 'dd']
tup= tuple(test_two)
for name in test_one.keys():
    print(name.title())
    for each in tup:
        if each in test_one:
            print(each + test_one[name])
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-14 19:52:00 | 显示全部楼层
感谢各位大神
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 06:17

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表