我可以用这种方式使用字典吗?

时间:2016-02-06 09:51:29

标签: python dictionary

我目前正在修改我的GCSE课程。我被要求的任务是一个故障排除程序,用户说出他们的问题;在将文本文件提取到代码中并打印相应的解决方案之前,我会评估他们的输入并测试它是否为关键字。

这是我的原始代码:

String exampleOfWhatStrLineReturns ="2016-02-06 10:19:36,410 INFO  [[RequestMappingHandlerMapping]]: I am an important log [123, 21] ...{.....}";

String id = "123";
String anotherValueIWant = "21";
String timestampString = "2016-02-06 10:19:36,410";

然而,在我的评估过程中,我意识到你无法为每个关键字打印解决方案。所以我决定让它为不同的列表赋值,然后有很多行

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])

依旧......

然而这是低效的;(无论如何我可以使用带有值的DICTIONARY并说出以下内容:

if list[1] and list[5] = "true: print(Solution[1] (更多组合) 然后像(可能是一个循环)

dictionary = [list[1] list[5],

3 个答案:

答案 0 :(得分:3)

你可以做到

keywords = ["battery", "off", "broken"]
question_about_phone = input("What Seems to be the Problem?")

with open('code.txt', 'r') as file:
    solutions = {k:line.strip(',\n') for k, line in zip(keywords, file)}
    answers = [v for k, v in solutions.items() if k in question_about_phone]

if answers:
    print(answers)
else:
    print('Sorry, there are no answers to your question')

,例如,文件

answer 4 battery
answer 4 off
answer 4 broken
...

和输入问题

What Seems to be the Problem? broken battery sunny

产生

['answer 4 broken', 'answer 4 battery']

基本上solutions构建了关键字和文件的每一行。

然后形成answers,选择问题中出现的关键字的值

然而,我非常同意Tim Seed的方法:仅查找问题中存在的关键字而不是反过来会更有效率,因为可能的答案数量超过了问题。

为了达到这个目的,只需更改

即可
answers = [solutions[k] for k in question_about_phone.split() if k in solutions]

答案 1 :(得分:2)

您已正确推断迭代列表(数组)效率低下 - 并且使用字典是一种选择。

所以使用你的例子

keywords = {"k1": "Turn Power on","k2":"Turn Power Off"}
for k in ['Bad','k1','k2','bad']:
  if k in keywords:
    print("%s: Answer is %s"%(k,keywords[k]))
  else:
    print("%s: No idea what the issue is"%(k))

你应该得到k1,k2的答案 - 但不是其他人......

给你输出

Bad: No idea what the issue is
k1: Answer is Turn Power on
k2: Answer is Turn Power Off 
bad: No idea what the issue is

希望有所帮助

答案 2 :(得分:2)

我假设每个关键字只有一个答案(来自您的示例代码)。

然后您可以在找到第一个答案后返回,如:

for x in range(0, 10):
    if keywords[x] in question_about_phone:
        print(solution[x])
        return
print("No solution found, be more specific")

您还可以以更一般的方式进行迭代:

for idx, kw in enumerate(keywords):
    if kw in question_about_phone:
        print(solutions[idx])
        return