这是一个非常基本的问题,但这里是:
我想创建一个数组,然后将用户输入与数组中的元素进行比较。
如果有一个元素匹配,则函数1将运行。如果两个元素在数组中匹配,则会运行另一个函数,依此类推。
目前,我只能使用没有链接到数组的IF语句,如下所示:
def stroganoff():
print ("You have chosen beef stroganoff")
return
def beef_and_ale_pie():
print ("You have chosen a beef and ale pie")
return
def beef_burger():
print ("You have chosen a beef burger")
return
ingredients = ['beef','mushrooms','ale','onions','steak','burger']
beef = input("Please enter your preferred ingredients ")
if "beef" in beef and "mushrooms" in beef:
stroganoff()
elif "beef" in beef and "ale" in beef:
beef_and_ale_pie()
elif "beef" in beef and "burger" in beef:
beef_burger()如上所述,这对你们中的一些人来说是基本的东西,但感谢你们的关注!
发布于 2016-10-08 11:10:46
因为您只能使用IF语句
beef=input().split()
#this splits all the characters when they're space separated
#and makes a list of them您可以使用您的"beef" in beef and "mushrooms" in beef,它应该会像您预期的那样运行
发布于 2016-10-08 07:32:15
所以我理解你的问题,你想知道用户输入了多少ingredients:
ingredients = {'beef','mushrooms','ale','onions','steak','burger'}
# assume for now the inputs are whitespace-separated:
choices = input("Please enter your preferred ingredients ").split()
num_matches = len(ingredients.intersection(choices))
print('You chose', num_matches, 'of our special ingredients.')发布于 2016-10-08 07:36:48
你可以这样做:
# Dictionary to map function to execute with count of matching words
check_func = {
0: func_1,
1: func_2,
2: func_3,
}
ingredients = ['beef','mushrooms','ale','onions','steak','burger']
user_input = input()
# Convert user input string to list of words
user_input_list = user_input.split()
# Check for the count of matching keywords
count = 0
for item in user_input_list:
if item in ingredients:
count += 1
# call the function from above dict based on the count
check_func[count]()https://stackoverflow.com/questions/39927044
复制相似问题