避免打印相同的输出

时间:2016-04-23 14:33:27

标签: python

我正在制作一个故障排除程序,它将要求用户输入,搜索一些列表以找到问题并为他们提供解决方案。

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",输出将被打印两次。我如何只打印一次?

2 个答案:

答案 0 :(得分:1)

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

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

break关键字将退出循环。

答案 1 :(得分: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"因为它匹配每个列表