首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数组python中选择多个元素

从数组python中选择多个元素
EN

Stack Overflow用户
提问于 2016-10-08 07:21:50
回答 3查看 123关注 0票数 0

这是一个非常基本的问题,但这里是:

我想创建一个数组,然后将用户输入与数组中的元素进行比较。

如果有一个元素匹配,则函数1将运行。如果两个元素在数组中匹配,则会运行另一个函数,依此类推。

目前,我只能使用没有链接到数组的IF语句,如下所示:

代码语言:javascript
复制
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()

如上所述,这对你们中的一些人来说是基本的东西,但感谢你们的关注!

EN

回答 3

Stack Overflow用户

发布于 2016-10-08 11:10:46

因为您只能使用IF语句

代码语言:javascript
复制
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,它应该会像您预期的那样运行

票数 1
EN

Stack Overflow用户

发布于 2016-10-08 07:32:15

所以我理解你的问题,你想知道用户输入了多少ingredients

代码语言:javascript
复制
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.')
票数 0
EN

Stack Overflow用户

发布于 2016-10-08 07:36:48

你可以这样做:

代码语言:javascript
复制
# 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]()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39927044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档