2016-04-23 72 views
0

我正在制作一个故障排除程序,它将要求用户输入,搜索某些列表以找出问题并给出解决方案。避免打印相同的输出

f=open('problem.txt') 
lines=f.readlines() 

problem1 = ["cracked", "phone", "screen", "dropped"] 
problem2 = ["charging", "port", "phone"] 
problem3 = ["slow", "phone", "freeze"] 

problem_input = input ("What is your problem? ") 
list_split = (problem_input.split()) 

for i in problem1: 
    if i in list_split: 
     print (lines[0]) 


for i in problem2: 
    if i in list_split: 
     print (lines[1])  

但是,如果我输入,"my phone is cracked",输出将被打印两次。我如何只打印一次?

+1

它打印了两次,因为它与第一循环和第二循环的相符程度。您可以实现AND条件逻辑或使用break –

回答

1

您正在骑单车查看问题案例列表,并且您的输入匹配两次。比赛是"phone""cracked"。为了防止这种情况,停在像第一场比赛:

for i in problem1: 
    if i in list_split: 
     print (lines[0]) 
     break 

break关键字将退出循环。

0

您正在循环查看“问题”列表并根据您的情况获取多个匹配项。

您可以通过制作成一个功能这return您的匹配问题:

f=open('problem.txt') 
lines=f.readlines() 

problem1 = ["cracked", "screen", "dropped"] 
problem2 = ["charging", "port"] 
problem3 = ["slow", "freeze"] 
problems = [problem1, problem2, problem3] 

def troubleshoot(): 
    problem_input = input("What is your problem? ") 
    list_split = (problem_input.split()) 
    for idx, problem in enumerate(problems, 1): 
     if any(i in problem for i in list_split): 
      return "problem{}".format(idx) 
      # or return lines[0] 

它将为以下运行:

>>> troubleshoot() 
What is your problem? my phone is slow and freezing up 
'problem3' 
>>> troubleshoot() 
What is your problem? my phone is not charging 
'problem2' 
>>> 
>>> troubleshoot() 
What is your problem? my phone dropped and the screen is cracked 
'problem1' 

或者,如果没有具有"phone"原因在每个problem列表中,您最好在此使用dict

problems = {'cracked':1, 'screen':1, 'dropped':1, 
      'charging':2, 'port':2, 
      'slow':3, 'freeze':3} 

user_problems = {problems[i] for i in problem_input.split()} 

注:我删除"phone"来自这两个,因为它为每一个列表