我正在尝试编写一个计算食物中营养水平的程序。假设我有这些数据(可能不正确)
10 grams of bread has 68 mg sodium.
1 medium slice is 50 grams.
1 cup of milk has 98 mg sodium
1 cup of milk is 236 ml(or 244 grams)
which means 10 grams of milk has 0.004 grams of Sodium
用户可以输入他吃的面包片数或克数,或者是否是牛奶 - 多少杯或他喝多少毫升的牛奶
那么,我应该如何设计数据结构?我应该像克一样在内部保留一个单位单位,并将切片,ml,杯等转换成那个?
food details ={
'whitebread':{'unit':10,'slice':50,'sodium':0.068},
'milk':{'unit':10,'cup':244,'sodium':0.004},...
}
答案 0 :(得分:1)
当然,您应该在内部转换为单个测量单位,并在输入和输出时进行转换。
在python中比在dynamically typed中更重要 - 你无法明确声明函数使用或返回的类型。考虑一个例子:
def get_sodium_for_bread(quantity_of_bread):
...
return quantity_of_sodium
您无法在C(quantity_...
)中明确定义miligrams_t get_sodium(slices_t bread)
变量的类型。如果你使用不同的单位,你会很快迷路。
如果可能的话,如果您使用单个单元,那将是最简单的,例如克
food_props_per_gram = {
'bread': {'sodum': 0.000012},
'milk': {'sodium': 0.00032}
}
units_to_grams = {
'slice': 100.0,
'cup': '250.0'
}
答案 1 :(得分:1)
一个简单的表示是named tuples。只要您不需要全面的面向对象设计,它们就可以了。
from collections import namedtuple
details = namedtuple('details', 'name sodium amount unit')
food = namedtuple('food', 'details amount unit')
unit = namedtuple('unit', 'name weight')
gram = unit('gram', 1)
slice = unit('slice', 50)
cup = unit('cup', 244)
bread = details(name='bread', sodium=68, amount=10, unit=gram)
f_bread = food(details=bread, amount=1, unit=slice)
milk = details(name='milk', sodium=98, amount=1, unit=cup)
f_milk = food(details=milk, amount=10, unit=gram)
for f in (f_bread, f_milk):
total = 1.0 / 1000 * f.amount * f.unit.weight * f.details.sodium / f.details.amount / f.details.unit.weight
print(
"%d %s of %s has %0.3f grams sodium" %
(f.amount, f.unit.name, f.details.name, total))
输出:
1 slice of bread has 0.340 grams sodium
10 gram of milk has 0.004 grams sodium
我从实际的食物摄入量中切出食物细节和单位。一种面包可能不止一次吃过。