[英]Avoid printing identical output
我正在制作一個故障排除程序,該程序將要求用戶提供輸入,搜索一些列表以查找問題並提供解決方案。
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"
,則輸出將被打印兩次。 我如何只打印一次?
您正在遍歷問題案例列表,並且輸入匹配兩次。 匹配是"phone"
和"cracked"
。 為了防止這種情況,請在第一個比賽中停下:
for i in problem1:
if i in list_split:
print (lines[0])
break
break
關鍵字將退出循環。
您正在遍歷“問題”列表,並獲得針對您狀況的多個匹配項。
您可以通過將其轉化為函數來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'
另外,如果沒有理由在每個problem
列表中都包含"phone"
,則最好在此處使用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"
,因為它與每個列表都匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.