我需要将用户输入与列表中的某些关键字相匹配。
我已经尝试了几种方法来做到这一点,使用 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
如果输入与关键字不匹配,我还需要代码来打印响应。目前找到关键字,但如果用户在关键字后面输入任何内容,就会出错。
最佳答案
您不需要这些疯狂的循环。
只是简单的
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!")
关于python - 遍历用户输入和列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480165/