如果我想让用户输入一个字符串列表,我怎么能检查这些字符串是否与已定义的列表匹配?这是我试过的:
Cake = ["Flour", "Eggs", "Milk"]
Burger = ["Beef", "Buns", "Lettuce", "Cheese"]
Hot_Dog = ["Sausage", "Buns", "Ketchup", "Mustard"]
my_list = [Cake, Burger, Hot_Dog]
ingredients = input("I have: ")
if (ingredients == Hot_Dog or Burger or Cake):
print(my_list)
else:
print("Nothing here")
我知道这并不是我想要的。我的目的是让它从用户给出的成分中返回你可以制作的东西。所以,如果我输入"面粉" "鸡蛋" &" Milk",它会打印出#34; Cake"
答案 0 :(得分:2)
如果您需要匹配成分然后打印出可以用它们制作的东西,请考虑使用词典作为主要数据结构。这使得成分列表与实际名称之间的对应关系非常容易使用:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/xxx");
Connection conn = ds.getConnection();
如果某些成分匹配,这些将使打印my_recipes = {
'Cake':["Flour", "Eggs", "Milk"],
'Burger':["Beef", "Buns", "Lettuce", "Cheese"],
'Hot_Dog' : ["Sausage", "Buns", "Ketchup", "Mustard"],
}
变得更容易。
然后你可以采取一些'Cake'
和input
(默认的空白字符):
split
并浏览字典ingredients = input("I have: ").split()
中的食谱以匹配它们:
my_recipes
答案 1 :(得分:0)
由于您只关心成分,而不关心它们的顺序,因此请使用集合和设置操作:
func GetLetterGoodness() []float32 {
return [...]float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}
顺便说一下,Cake = set(["Flour", "Eggs", "Milk"])
Burger = set(["Beef", "Buns", "Lettuce", "Cheese"])
Hot_Dog = set(["Sausage", "Buns", "Ketchup", "Mustard"])
my_list = [Cake, Burger, Hot_Dog]
ingredients = set(input("I have: ").split())
for food in my_list:
if not(food - ingredients):
print(food)
是一组缺失的成分。
答案 2 :(得分:0)
以下是解决此问题的简单示例:
cake_ingredients = ["Flour", "Eggs", "Milk"]
burguer_ingredients = ["Beef", "Buns", "Lettuce", "Cheese"]
hot_dog_ingredients = ["Sausage", "Buns", "Ketchup", "Mustard"]
my_list = {
'cake': cake_ingredients,
'burguer': burguer_ingredients,
'hot_dog': hot_dog_ingredients
}
ingredients = "FlOur EGGs MiLk"
for k, v in my_list.items():
v = set([ing.lower() for ing in v])
remaining_ingredients = (
v - set([ing.lower() for ing in ingredients.split()]))
if len(remaining_ingredients) == 0:
print("You got enough ingredients to make a {0}".format(k))
else:
print("You'd still need {0} to make a {1}".format(
','.join(remaining_ingredients), k
))