因为编程是我最喜欢的爱好之一,所以我在python中开始了一个小项目。
我正在尝试为日常生活制作营养计算器,请参阅以下代码:
# Name: nutri.py
# Author: pyn
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food: ")
#explode / split the user input
foods_list = foods.split(',')
#returns a list separated by comma
print foods_list
我想做什么:
欢迎任何想法。
答案 0 :(得分:0)
my_dict = {'chicken':(40, 50, 10),
'beef':(50, 30, 20)
}
foods = raw_input("Enter your food: ")
#explode / split the user input
foods_list = foods.split(',')
#returns a list separated by comma
#print foods_list
nuts = [0, 0, 0]
for food in foods_list :
if food.strip() in my_dict:
i = 0
for value in my_dict[food.strip()]:
nuts[i] += value
i += 1
print nuts
scripts$ python nutrition.py
Enter your food: chicken, pork, beef
[90, 80, 30]
some improvements ;)
答案 1 :(得分:0)
此代码将执行您尝试执行的所有必要操作:
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food: ")
#explode / split the user input
foods_list = foods.split(',')
#returns a list separated by comma
t=[0,0,0]
print foods_list
for i in foods_list:
if i.strip() in my_dict:
v=my_dict.get(i.strip())
t[0]=t[0]+v[0]
t[1]=t[1]+v[1]
t[2]=t[2]+v[2]
print t
答案 2 :(得分:0)
这是我的解决方案,它检查食物是否在字典中,并说明它是否不存在。
my_dict = {'chicken':(40, 50, 10),
'pork':(50, 30, 20)
}
foods = raw_input("Enter your food: ")
foods_list = foods.split(',')
empty_list = []
for food in foods_list:
if food in my_dict:
empty_list.append(list(my_dict[food]))
else:
print '%s has no nutritional information and will not be included in the calculation' % food
values = [sum(x) for x in zip(*empty_list)]
print 'Total protein = %d, Total Carbs = %d, Total Fat = %d' % (values[0],values[1],values[2])
输出:
Enter your food: chicken,pork,pizza
pizza has no nutritional information and will not be included in the calculation
Total protein = 90, Total Carbs = 80, Total Fat = 30