【问题标题】:Partial match in a list, from a user input列表中的部分匹配,来自用户输入
【发布时间】:2016-02-24 23:46:10
【问题描述】:

尝试从用户输入中获取列表中的部分匹配项。

我正在尝试制作一个简单的诊断程序。用户输入他们的疾病,程序将输出建议的治疗方法。

print("What is wrong with you?")
answer=input()
answer=answer.lower()

problem=""
heat=["temperature","hot"]
cold=["freezing","cold"]

if answer in heat:
    problem="heat"
if answer in cold:
    problem="cold"

print("you have a problem with",problem)

我可以让它从列表中选择一个完全匹配,但我希望它从我的输入中找到部分匹配。例如,如果用户键入他们“太热了”。

【问题讨论】:

    标签: list python-3.x


    【解决方案1】:

    试试下面的代码。关键是split() 方法。

    answer = input('What is wrong with you?')
    answer = answer.lower()
    
    heat = ['temperature', 'hot']
    cold = ['freezing', 'cold']
    
    for word in answer.split():
        if word in heat:
            problem = 'heat'
        if word in cold:
            problem = 'cold'
    
    print('you have a problem with', problem)
    

    【讨论】:

      【解决方案2】:

      我建议你使用这样的东西,它可能更“pythonic”

      answer = input()
      cold = ["freezing", "cold"]
      if any(answer in c for c in cold):
          problem = "cold"
      

      【讨论】:

        猜你喜欢
        • 2013-11-24
        • 2020-12-30
        • 1970-01-01
        • 2021-11-27
        • 1970-01-01
        • 2021-10-27
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多