这是一个非常基本的问题,但这里有:
我想创建一个数组,然后想将用户输入与数组中的那些元素进行比较。
如果匹配一个元素,那么函数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()
如上所述,对于你们中的一些人来说这是基本的东西,但是谢谢你的期待!
答案 0 :(得分:0)
因此,我了解您的问题,以便您想知道用户输入了多少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.')
答案 1 :(得分:0)
您可以执行以下操作:
# 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]()
答案 2 :(得分:0)
因为您只能使用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
,它应该按预期运行