迭代用户输入和列表

时间:2016-04-07 15:05:39

标签: python iteration

我需要将用户输入与列表中的某些关键字进行匹配。

我尝试了几种方法,使用for,if和while。即使是枚举也是最好的,但似乎无法把它放在一起。我需要考虑用户可能输入的几个单词。最终,代码将与其他内容相关,并打开与关键字相关的文件。

示例代码:

shopping = [
    'bananas',
    'apples',
    'chocolate',
    'coffee',
    'bread',
    'eggs',
    'vimto'
    ]

need = input ("please input what you need ")
need = need.lower()
need = need.split()
index = 0
while index < len(shopping):
    for word in need:
        if word == shopping[index]:
            print ("Added to basket")
            index +=1

        if word != shopping[index]:
            index +=1

如果输入与关键字不匹配,我还需要代码来打印响应。目前找到关键字,但如果用户在关键字后输入任何内容,则会发生错误。

2 个答案:

答案 0 :(得分:5)

你不需要这些疯狂的循环。

只是简单地

if thing in shopping_list:
    # this is good!
else:
    # do something

总而言之,您的代码将如下所示:

need = input("Input what you need: ")
need = [x.strip() for x in need.lower().strip().split()]

for thing in need:
    if thing in shopping_list:
        print("Added this!")
    else:
        print("No, man, you aren't buying this!")

答案 1 :(得分:1)

试试这个:

shopping = [
    'bananas',
    'apples',
    'chocolate',
    'coffee',
    'bread',
    'eggs',
    'vimto'
    ]

need = input ("please input what you need ")
need = need.lower()
need = need.split()
error = False
for word in need:
    if word in shopping:
        pass
    else:
        error = True

if Error: print ("Not on the list")
else: print ("Added to basket")