多个输入和搜索

2024-04-29 05:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

因为编程是我最喜欢的爱好之一,所以我用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

我想做的是:

  1. 获取用户输入并将其存储在变量中
  2. 根据用户输入搜索字典,如果存在键/食物,则返回相关值
  3. 把这些值加在不同的营养块上,然后返回,比如:你吃了x蛋白,y碳水化合物和z脂肪等等

欢迎提出任何意见。你知道吗


Tags: 项目代码用户namepyinput编程计算器
3条回答

这是我的解决方案,它检查一种食物是否在字典里,如果没有,它会说明。你知道吗

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

这段代码将完成您正在尝试执行的所有必要操作:

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
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 ;)

相关问题 更多 >