更有效的列表功能和提问/回答方式?

时间:2016-02-06 12:46:57

标签: python list dictionary

我制作了一个问题排查工具,我的GCSE根据用户输入提供了合适的答案。我原来的代码是:

keywords = ["k1","k2","k3","k4","k5","k6","k7","k8","k9","kk"]

question_about_phone = input("What Seems to be the Problem? Please be percific but don't bombard us with too much info").lower()

file = open('code.txt','r')
solution = [line.strip(',') for line in file.readlines()]

for x in range(0, 10):
    if keywords[x] in question_about_phone:
        print(solution[x])

然而,发生的事情是我的老师告诉我,我不能堆叠解决方案,例如k1和k3一起最终无法合并k1和k3解决方案但必须提出单独的解决方案。

因此,这就是我所做的:

keywords = ["k1","k2","k3","k4","k5","k6","k7","k8","k9","kk"]
true = ["False","False","False","False","False","False","False","False","False","False"]
question_about_phone = input("What Seems to be the Problem? Please be percific but don't bombard us with too much info").lower()
file = open('code.txt','r')
solution = [line.strip(',') for line in file.readlines()]

for x in range(0, 10):
    if keywords[x] in question_about_phone:
        true == "true"

if true[1] == "true" and true[2] == "true" and true[3] == "true":
    print(solution[1])

if true[1] == "true" and true[3] == "true" and true[5] == "true":
    print(solution[2])

if true[1] == "true" and true[7] == "true" and true[8] == "true":
    print(solution[3])

if true[8] == "true" and true[4] == "true" and true[5] == "true":
    print(solution[4])

if true[6] == "true" and true[9] == "true" and true[4] == "true":
    print(solution[5])

if true[3] == "true" and true[4] == "true" and true[8] == "true":
    print(solution[6])

if true[1] == "true" and true[9] == "true" and true[2] == "true":
    print(solution[7])

if true[10] == "true" and true[1] == "true" and true[9] == "true":
    print(solution[8])

if true[3] == "true" and true[7] == "true" and true[10] == "true":
    print(solution[9])

if true[7] == "true" and true[3] == "true" and true[4] == "true":
    print(solution[10])

现在有什么方法可以简化这个,或者我必须这样做。非常感谢,谢谢

1 个答案:

答案 0 :(得分:3)

我认为可以使用一些词典来存储解决方案:

solutions = {
    solution[1]: [1, 2, 3], 
    solution[2]: [1, 3, 5],
    solution[3]: [1, 7, 8], 
    ...
}

所以你可以做这样的事情

for answer, questions in solutions.items():
    if all([true(x)=="true" for x in questions]):
        print answer
        break