编辑
进行建议的更改后不再出现列表错误,但仍不返回任何匹配项。现在代码:
# 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]
#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()
tuple(iP)
#compare iP to allRec looking for matches
if iP in allRec:
matches = set (iP) & set(allRec)
print ("Matches:",matches)
尝试将其打印出匹配的配方,并在可能的情况下标记配方本身的名称。
答案 0 :(得分:2)
列表不可散列,因为可以在运行时对其进行修改。因此,请尝试使用(不可更改的)元组而不是列表-您可以使用括号而不是括号来定义r1
至r4
,并在排序后将iP
转换为元组。然后,您可以使用没有问题的元组集。
答案 1 :(得分:1)
这是因为allRes
是列表的列表。不能转换为Set。
要获取配方或配方的索引,可以使用以下代码段。
index = allRec.index(iP)
recipe = allRec[index]
您无需将所有食谱更改为该食谱;如果配料的输入顺序不同。