Python 遍历用户输入和列表
我需要将用户输入与列表中的一些关键字相匹配 我尝试了几种方法来实现这一点,使用for、if和while。甚至认为列举是最好的,但似乎不能把它放在一起。我需要考虑用户可能输入的几个词。最终,代码将与其他内容相关,并打开与关键字相关的文件 示例代码:Python 遍历用户输入和列表,python,iteration,Python,Iteration,我需要将用户输入与列表中的一些关键字相匹配 我尝试了几种方法来实现这一点,使用for、if和while。甚至认为列举是最好的,但似乎不能把它放在一起。我需要考虑用户可能输入的几个词。最终,代码将与其他内容相关,并打开与关键字相关的文件 示例代码: shopping = [ 'bananas', 'apples', 'chocolate', 'coffee', 'bread', 'eggs', 'vimto' ] need = in
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
购物=[
“香蕉”,
“苹果”,
“巧克力”,
“咖啡”,
“面包”,
“鸡蛋”,
“维姆托”
]
需要=输入(“请输入您需要的内容”)
need=need.lower()
need=need.split()
索引=0
而指数
如果输入与关键字不匹配,我还需要代码来打印响应。在找到关键字的那一刻,如果用户在关键字之后输入任何内容,就会出现错误。您不需要这些疯狂的循环 就这么简单
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!")
试试这个:
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")
谢谢,如果我在每个单词的“不在列表上”的关键字周围输入几个单词,很抱歉,这让我很痛苦,但是你知道如何阻止它,这样它只在用户输入的迭代结束时打印一次吗?非常感谢你,这让我变得过于复杂,无法从树中看到木头。