这是我的第一个小项目和第一个问题,对于格式化很抱歉。我有两个包含食谱名称的列表作为字符串。我想问用户他们想要的每个列表中有多少餐,然后随机选择。
然后,我想检查选择是否选择了一顿饭,并显示我将存储在一个变量中的膳食价格。
我的想法是将随机样本添加到新列表中,并通过if in语句检查内容。如果配方在新列表中,那么它将打印包含价格的变量。
但是,当我检查配方的新列表时,它并不认为它在列表中。有没有我错过的东西或更好的方法吗?谢谢。
到目前为止我的代码:
import random
Vegetarian = ["Jungle Curry", "Chickpea Curry", "Dhal", "Buddha Bowl",
"Chickpea Salad", "Lazy Noodles", "Fry Up"]
Meat = ["Chilli", "Butter Chicken", "Lamb and Hummus"]
v = int(raw_input("How many vegetarian meals this week? > "))
m = int(raw_input("How many meaty meals? > "))
Veg1 = random.sample(Vegetarian, v)
Meat2 = random.sample(Meat, m)
veg_week = []
meat_week = []
veg_week.append(Veg1)
meat_week.append(Meat2)
jungle_curry = 10
chickpea_curry = 10
if "Jungle Curry" and "Chickpea Curry" in veg_week:
print jungle_curry + chickpea_curry
答案 0 :(得分:1)
你有几个错误,让我们来看看:
random.sample
的结果是一个列表;当你打电话给veg_week.append(Veg1',你正在创建一个列表列表。10
分配给jungle_curry
和chickpea_curry
"Jungle Curry"
和"Chickpea Curry"
;也许你想逐一检查这些是否在本周的菜单中?这应该更好:
import random
Vegetarian = ["Jungle Curry", "Chickpea Curry", "Dhal", "Buddha Bowl",
"Chickpea Salad", "Lazy Noodles", "Fry Up"]
Meat = ["Chilli", "Butter Chicken", "Lamb and Hummus"]
v = int(input("How many vegetarian meals this week? > "))
m = int(input("How many meaty meals? > "))
Veg1 = random.sample(Vegetarian, v)
Meat2 = random.sample(Meat, m)
if "Jungle Curry" and "Chickpea Curry" in veg1:
print(jungle_curry + chickpea_curry)
答案 1 :(得分:0)
我会这样做的
import random
Vegetarian = ["Jungle Curry", "Chickpea Curry", "Dhal", "Buddha Bowl",
"Chickpea Salad", "Lazy Noodles", "Fry Up"]
Meat = ["Chilli", "Butter Chicken", "Lamb and Hummus"]
v = int(raw_input("How many vegetarian meals this week? > "))
m = int(raw_input("How many meaty meals? > "))
Veg1 = random.sample(Vegetarian, v)
Meat2 = random.sample(Meat, m)
veg_week = []
meat_week = []
veg_week.append(Veg1)
meat_week.append(Meat2)
# put the prices of each in the list too
Vegetarian_price = [10, 10, 10, 10, 10, 10, 10]
Meat_price = [20, 20, 20]
v_cost = 0
m_cost = 0
for i in range(len(Veg1)):
v_cost += Vegetarian_price[Vegetarian.index(Veg1[i])]
for i in range(len(Meat2)):
m_cost += Meat_price[Meat.index(Meat2[i])]
print v_cost,m_cost