简体   繁体   English

在嵌套列表中搜索

[英]Searching within nested list

EDIT编辑

No longer getting list error after making suggested changes but still not returning any matches.进行建议的更改后不再出现列表错误,但仍未返回任何匹配项。 Code now:现在代码:

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

Trying to get it print out which recipe matched and if possible tag the name of the recipe itself.试图让它打印出匹配的配方,并在可能的情况下标记配方本身的名称。

Lists are unhashable since they can be modified during runtime.列表是不可散列的,因为它们可以在运行时修改。 So instead of lists, try using (non-mutable) tuples - you can define r1 through r4 using parentheses instead of brackets, and convert iP to a tuple after sorting.因此,不要使用列表,而是尝试使用(非可变)元组 - 您可以使用圆括号而不是方括号定义r1r4 ,并在排序后将iP转换为元组。 You can then use sets of tuples with no issues.然后,您可以毫无问题地使用多组元组。

This is because of allRes is a list of the list.这是因为allRes是一个列表列表。 Which cannot be converted to the Set.无法转换为 Set。

To get the index of the recipe or recipe you can use the following snippet.要获取配方或配方的索引,您可以使用以下代码段。

index = allRec.index(iP)
recipe = allRec[index]

You will need no change all the recipes to the set;您无需将所有食谱更改为该套装; if ingredients are entered in a different order.如果成分以不同的顺序输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM