我正在python 3.7上尝试一个小的pep项目,但似乎无法使它正常工作。我想找到一个存储在包含多个列表的对象中的给定列表。我敢肯定我的编码方式还不错,因为我是这个新手!
my_choice = ["a", "b", "c"]
reciepe1 = [["a", "b", "c"], "d", "e", "f"]
reciepe2 = ["x", "y", "z"]
menu = [reciepe1, reciepe2]
for my_choice in menu:
if my_choice in reciepe1:
print(reciepe1)
elif my_choice in reciepe2:
print(reciepe2)
答案 0 :(得分:0)
您的逻辑几乎是正确的,您只是弄乱了变量,实际上并不需要elif
:
my_choice = ["a", "b", "c"]
recipe1 = [["a", "b", "c"], "d", "e", "f"]
recipe2 = ["x", "y", "z"]
menu = [recipe1, recipe2]
for recipe in menu:
if my_choice in recipe:
print(recipe)
输出
[['a', 'b', 'c'], 'd', 'e', 'f']
答案 1 :(得分:0)
# possible successful my_choices are from --> ["a", "b", "c"], "d", "e", "f", "x", "y", "z",
# In case your my_choice is --> "a", then you have to **flatten** the list of all reciepe's.
my_choice = ["a", "b", "c"]
#create a dictionary as follows:
reciepe_final = {"reciepe1": [["a", "b", "c"], "d", "e", "f"],
"reciepe2" : ["x", "y", "z"]}
#loop through the key and values of each reciepe
for k, i in reciepe_final.items():
#if my_choice found in values print the key (reciepe(n))
if my_choice in i: print (k)
#result --> reciepe1
如果您想弄平列表,然后在堆栈溢出/ google中搜索,或者让我知道,我会为您提供代码。