不可散列类型

问题描述 投票:0回答:2
# all ingredients, represented by numbers: 0= empty selection 1=rice 2=spice 3=vegetable 
allIng = [0,1,2,3]

#Each individual recipe(r)


# Veggie Rice Balls
r1 = (0,1,3)

# Curry Rice
r2 =(0,1,2)

# Herb Sauté
r3 = (0,2,3)

# Vegetable Curry
r4 = (1,2,3)


# all recipes on one list 

allRec = [r1,r2,r3,r4]
allRecNames = {(0,1,3): 'Veggie Rice Balls', (0,1,2): 'Curry Rice', (0,2,3): 'Herb Sauté', (1,2,3): 'Vegetable Curry'}


#ingredients picked
iP = []
#ingredient count
iC = 1

#User given option to pick up to 3 ingredients
while iC <= 3:
    pitem = int (input ("Pick up to 3 items "))

    if pitem in allIng:
        iP.append(pitem)
        print(iP)
        iC += 1
    else:
        print ("Incorrect entry, please pick again")

#sort list
iP.sort()
iP = tuple(iP)

#compare iP to allRec looking for matches
if iP in allRec:

    match = set ([iP]) & set(allRec)
    print ("Match:",match)
    allRecNames[match]

大家好,

[尝试获取我的代码以打印出与各自匹配的菜肴名称。例如,如果我输入0,1,3,我将返回素食汤圆。

当前错误:TypeError:不可散列的类型:'设置'

如果我错了,请纠正我和ELI5,但这是否意味着我需要先将匹配项转换为可哈希的内容:

 allRecNames[match]

之前有人在我的代码中推荐了元组转换,并认为我也可以在此处执行类似的操作,但不会出错。

与往常一样,如果能提供帮助,我们将不胜感激。

python python-3.x
2个回答
1
投票

[将其用作字典键之前,请先尝试:

match = frozenset(match)

问题是match是可修改的set,因此它不能用作字典键。通过使用frozenset,我们使其不可变,因此我们可以将其用作键。


0
投票

字典中的键是元组,因此您需要使用元组来访问它。幸运的是,iP是一个元组,并且您已经知道它是字典中的键,因为这是您的if语句所测试的。

因此,您只需要将allRecNames[match]更改为allRecNames[iP]

就是说,这条线本身什么也不做;它只是从字典中获取一个值,但不将该值用于任何东西。您可能要打印它,因此在这种情况下,它应该是print(allRecNames[iP])

© www.soinside.com 2019 - 2024. All rights reserved.