【问题标题】:Finding the values corresponding with user input from a list of tuples从元组列表中查找与用户输入对应的值
【发布时间】:2020-10-21 01:01:11
【问题描述】:

作为前言,我对 python 还是很陌生,而且一般都是编码。

我正在尝试获取以下代码以在 foodgroups 元组中查找与用户输入匹配的特定值(即:乳制品、坚果和谷物)并将它们附加到 Output(即:乳制品和坚果)。当我第一次做这个时,Output 的行是从another website 得到的。当用户提供的输入仅包含一个项目而没有任何符号或空格(即:Dairy)但任何额外内容会导致 Output 在打印时为空白时,该代码才有效。

userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
foodgroups = ("Dairy","Nuts","Seafood","Chocolate")

Output = list(filter(lambda x:userinput in x, foodgroups))

if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
  print(Output,"is present in your list, " + userinput)
else:
  print("Negative.")

我曾想过交换foodgroupsuserinput,但这会导致TypeError,并且将元组转换为字符串时Output 总是返回空白。

我问过其他人如何解决这个问题,但他们的运气并没有好到哪里去。任何帮助表示赞赏!

【问题讨论】:

    标签: python


    【解决方案1】:

    如果用户输入是逗号分隔的字符串,则将其拆分并使用列表:

    userinput = input("Enter foodgroups ate in the last 24hrs : ")
    foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
    uin = userinput.split(",")
    grp = []
    for x in uin:
      if x in foodgroups:
        grp.append(x)
    

    grp是foodgroup中用户定义的食物

    【讨论】:

    • 或者,如果允许库,您可以先执行import pandas as pd,然后执行grp=pd.Series(uin).isin(foodgroup) 以避免循环
    【解决方案2】:

    主要是您想使用split 将用户输入中的单个单词分隔成单词列表。我还在你的 lambda 中交换了 xseafoods

    如果用户用一个或多个空格分隔每个单词,以下是更改代码以使其正常工作的方法:

    userinput = input("Enter foodgroups ate in the last 24hrs : ").title()
    foodgroups = ("Dairy","Nuts","Seafood","Chocolate")
    
    userfoods = userinput.split()
    
    Output = list(filter(lambda x: x in userfoods, foodgroups))
    
    print(Output,"is present in your list, " + str(userinput))
    

    【讨论】:

      【解决方案3】:

      正如其他人所说,您需要使用split() 来分隔输入中的各个项目:

      userfoods = userinput.split()
      

      但即使在那之后您的if 条件也不正确:

      if foodgroups[0] or foodgroups[1] or foodgroups[2] or foodgroups[3] in userinput:
      

      这里要意识到orin与紧邻的两个值一起使用的运算符。我们可以添加括号来看看它是如何工作的:

      if (((foodgroups[0] or foodgroups[1]) or foodgroups[2]) or (foodgroups[3] in userinput)):
      

      这意味着foodgroups[0] or foodgroups[1] 的计算结果只是foodgroups[0] 的值,所以foodgroups[1] 基本上被忽略了。这不是你想要的。相反,您需要为每个项目检查in

      if foodgroups[0] in userinput or foodgroups[1] in userinput or foodgroups[2] in userinput or foodgroups[3] in userinput:
      

      但正如您所见,这会变得非常冗长。因此,正如其他人已经展示的那样,使用循环或列表推导或生成器表达式可以减少您需要编写的代码量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        • 2021-06-24
        相关资源
        最近更新 更多