【问题标题】:finding a given list from storage/bank of lists从存储/列表库中查找给定列表
【发布时间】:2018-12-01 09:34:56
【问题描述】:

我正在 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)  

【问题讨论】:

  • 迭代变量和选择变量相同。
  • @SinclairAkoto - 请通过单击对您最有帮助的答案左侧的复选标记来关闭您的问题。 :)

标签: python list loops for-loop


【解决方案1】:

你的逻辑几乎是正确的,你只是弄乱了变量,你实际上并不需要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']

【讨论】:

  • 感谢现在看着我可以看到我哪里出错了,作为一个新手,我真的很感谢你的帮助!
【解决方案2】:

其中一种方法是使用字典,如下:

#  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 中搜索或告诉我,我将为您提供代码。

【讨论】:

  • 非常感谢,看看这个就明白了 - 试试这个,让你知道!
  • 非常感谢!我试过了,它奏效了!我想要的是能够打印食谱和食谱的内容,所以最后我输入了 print(k,i) ,它就像做梦一样!
  • @SinclairAkoto: 乐于助人.. :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2010-10-15
  • 2010-11-25
相关资源
最近更新 更多