python - 在嵌套列表中搜索
问题描述
编辑
做出建议的更改后不再出现列表错误,但仍未返回任何匹配项。现在编码:
# 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)
试图让它打印出匹配的配方,并在可能的情况下标记配方本身的名称。
解决方案
列表是不可散列的,因为它们可以在运行时修改。因此,不要使用列表,而是尝试使用(非可变)元组 - 您可以r1
通过r4
使用括号而不是括号来定义,并iP
在排序后转换为元组。然后,您可以毫无问题地使用元组集。
推荐阅读
- reactjs - React Native - 移动到 ViewPagerAndroid 中的另一个视图时如何立即显示 FlatList?
- react-native - 世博会问题启动应用程序(显示三个屏幕按钮) - React Native
- ubuntu - 无法链接到 libglew 或 libglfw
- vue.js - 在 vue 项目中设置全局 sass 变量
- jekyll - 使用包含标签访问 Jekyll 的 _data 文件夹中的 csv
- groovy - 如何解决 Groovy 错误“无法解析类 spock.lang.Specification”?
- model-view-controller - 通过 HTTPS 连接时 Ajax.BeginForm OnFailure 返回空结果
- javascript - 从头开始将 JS 数组传递给 PHP 以获取联系表单
- php - 无法从 symfony 3 中的 ajax 发布请求访问请求数据
- ocaml - Ocaml 将类型转换为字符串