2016-04-23 110 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"來自這兩個,因爲它爲每一個列表