来自用户输入的列表中的部分匹配

时间:2016-02-24 14:48:15

标签: list python-3.x

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

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

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)

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

2 个答案:

答案 0 :(得分:0)

尝试以下代码。关键是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)

答案 1 :(得分:0)

我建议你使用这样的东西,这可能会更多一些" pythonic"

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