虽然循环不是迭代在数组中的正确解决方案

时间:2016-06-22 16:13:35

标签: python arrays indexing while-loop counter

我的目标:我正在尝试让用户输入他们自己的查询以查找故障排除系统。如果用户的输入具有在'keywords'数组中找到的关键字,则会从'answers'数组中的相同索引给出解决方案。

问题:没有语法错误,但存在逻辑错误。对于'keywords'数组中的第一个和第二个索引,如果输入此关键字,则给出正确的解决方案。但是,对于'keywords'数组中的第三个和第四个索引,它会从'answers'数组中的不同索引输出错误的解决方案。

我的代码:

answers = ['dry it out','replace screen','delete any apps that are not needed','restart it']
keywords = ['wet','cracked','download','unresponsive']
i = 0
while i <= 5:
    user_query = str(input('What\'s the problem?\n>> ')).lower()
    for keyword in keywords:
        while keyword[i] not in user_query:
            i = i + 1
        if keyword[i] in user_query:
            print(answers[i])
            i = 10
            break
        if i >= 5:
            print('contact the supplier')
            break

3 个答案:

答案 0 :(得分:2)

您必须记住,在for keyword in keywords:中,关键字是一个字符串,并通过i对其进行索引会拉出单个字母。相反,你想做类似的事情:

for keyword in keywords:
    if keyword in user_query:
        # Handle things here

for i in range(len(keywords)):
    if keyword[i] in user_query:
         # Handle things here

第二种方法允许您引用answers数组中的相应条目,因此这是我推荐的内容。

您仍需要清理内容,并确保用户在代码中的正确位置输入查询。我的猜测是你想要的代码(尽管你应该验证)是:

answers = ['dry it out','replace screen','delete any apps that are not needed','restart it']
keywords = ['wet','cracked','download','unresponsive']
user_query = str(input('What\'s the problem?\n>> ')).lower()


for i in range(len(keywords)):
    if keyword[i] in user_query:
        print(answers[i])
        break
else:
    print('contact the supplier')

此代码使用附加到else循环的for块。要了解正在发生的事情,建议您仔细阅读here

答案 1 :(得分:2)

answers = ['dry it out','replace screen','delete any apps that are not needed','restart it']
keywords = ['wet','cracked','download','unresponsive']

query = input('What\'s the problem?\n>> ').lower()

try:
    print(answers[keywords.index(query)])
except ValueError:
    print("Contact the supplier.")

这是另一个使用index函数内置的列表而不需要for循环的选项。

答案 2 :(得分:1)

我认为这可能会有所改善:

answers = ['dry it out','replace screen','delete any apps that are not needed','restart it']
keywords = ['wet','cracked','download','unresponsive']
responses = {k:v for k,v in zip(keywords,answers)}

def getAnswer(query, solutions):
    for keyword in solutions:
        if keyword in query:
            return solutions[keyword]
    return "Contact the supplier"

user_query = str(input('What\'s the problem?\n>> ')).lower()
print(getAnswer(user_query,responses))

示例输出:

What's the problem?
>> screen cracked
replace screen