首页 > 解决方案 > 在嵌套列表中搜索

问题描述

编辑

做出建议的更改后不再出现列表错误,但仍未返回任何匹配项。现在编码:

# 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)

试图让它打印出匹配的配方,并在可能的情况下标记配方本身的名称。

标签: pythonpython-3.x

解决方案


列表是不可散列的,因为它们可以在运行时修改。因此,不要使用列表,而是尝试使用(非可变)元组 - 您可以r1通过r4使用括号而不是括号来定义,并iP在排序后转换为元组。然后,您可以毫无问题地使用元组集。


推荐阅读