food_nutrients = {(fn[0], nutrients[n].name):
fn[1 + n] for fn in FOOD_NUTRIENTS for n in range(len(NUTRIENTS))}
fn[0]输出FOOD_NUTRIENTS第1列,即食品名称;nutrients[n].name输出营养物质名称;fn[1 + n],n in range(0,7)输出FOOD_NUTRIENTS的第2~8列,即营养物质含量。
为了将原来的FOOD_NUTRIENTS字典变成food_nutrients中的多键值
形式,即{(食品i,营养物质j):值}
的形式,需要对每一种食品循环7次(7种营养物质)。这样我们就可以根据食品名称+营养物质名称,快速查找到各食物对应的不同营养含量。
最后得到:food_nutrients = {(‘Roasted Chicken’, ‘Calories’): 277.4, (‘Roasted Chicken’, ‘Calcium’): 21.9, (‘Roasted Chicken’, ‘Iron’): 1.8, (‘Roasted Chicken’, ‘Vit_A’): 77.4, (‘Roasted Chicken’, ‘Dietary_Fiber’): 0, (‘Roasted Chicken’, ‘Carbohydrates’): 0, (‘Roasted Chicken’, ‘Protein’): 42.2, (‘Spaghetti W/ Sauce’, ‘Calories’): 358.2, (‘Spaghetti W/ Sauce’, ‘Calcium’): 80.2, (‘Spaghetti W/ Sauce’, ‘Iron’): 2.3, (‘Spaghetti W/ Sauce’, ‘Vit_A’): 3055.2, (‘Spaghetti W/ Sauce’, ‘Dietary_Fiber’): 11.6, (‘Spaghetti W/ Sauce’, ‘Carbohydrates’): 58.3, (‘Spaghetti W/ Sauce’, ‘Protein’): 8.2, (‘Tomato,Red,Ripe,Raw’, ‘Calories’): 25.8, (‘Tomato,Red,Ripe,Raw’, ‘Calcium’): 6.2, (‘Tomato,Red,Ripe,Raw’, ‘Iron’): 0.6, (‘Tomato,Red,Ripe,Raw’, ‘Vit_A’): 766.3, (‘Tomato,Red,Ripe,Raw’, ‘Dietary_Fiber’): 1.4, (‘Tomato,Red,Ripe,Raw’, ‘Carbohydrates’): 5.7, (‘Tomato,Red,Ripe,Raw’, ‘Protein’): 1, (‘Apple,Raw,W/Skin’, ‘Calories’): 81.4, (‘Apple,Raw,W/Skin’, ‘Calcium’): 9.7, (‘Apple,Raw,W/Skin’, ‘Iron’): 0.2, (‘Apple,Raw,W/Skin’, ‘Vit_A’): 73.1, (‘Apple,Raw,W/Skin’, ‘Dietary_Fiber’): 3.7, (‘Apple,Raw,W/Skin’, ‘Carbohydrates’): 21, (‘Apple,Raw,W/Skin’, ‘Protein’): 0.3, (‘Grapes’, ‘Calories’): 15.1, (‘Grapes’, ‘Calcium’): 3.4, (‘Grapes’, ‘Iron’): 0.1, (‘Grapes’, ‘Vit_A’): 24, (‘Grapes’, ‘Dietary_Fiber’): 0.2, (‘Grapes’, ‘Carbohydrates’): 4.1, (‘Grapes’, ‘Protein’): 0.2, (‘Chocolate Chip Cookies’, ‘Calories’): 78.1, (‘Chocolate Chip Cookies’, ‘Calcium’): 6.2, (‘Chocolate Chip Cookies’, ‘Iron’): 0.4, (‘Chocolate Chip Cookies’, ‘Vit_A’): 101.8, (‘Chocolate Chip Cookies’, ‘Dietary_Fiber’): 0, (‘Chocolate Chip Cookies’, ‘Carbohydrates’): 9.3, (‘Chocolate Chip Cookies’, ‘Protein’): 0.9, (‘Lowfat Milk’, ‘Calories’): 121.2, (‘Lowfat Milk’, ‘Calcium’): 296.7, (‘Lowfat Milk’, ‘Iron’): 0.1, (‘Lowfat Milk’, ‘Vit_A’): 500.2, (‘Lowfat Milk’, ‘Dietary_Fiber’): 0, (‘Lowfat Milk’, ‘Carbohydrates’): 11.7, (‘Lowfat Milk’, ‘Protein’): 8.1, (‘Raisin Brn’, ‘Calories’): 115.1, (‘Raisin Brn’, ‘Calcium’): 12.9, (‘Raisin Brn’, ‘Iron’): 16.8, (‘Raisin Brn’, ‘Vit_A’): 1250.2, (‘Raisin Brn’, ‘Dietary_Fiber’): 4, (‘Raisin Brn’, ‘Carbohydrates’): 27.9, (‘Raisin Brn’, ‘Protein’): 4, (‘Hotdog’, ‘Calories’): 242.1, (‘Hotdog’, ‘Calcium’): 23.5, (‘Hotdog’, ‘Iron’): 2.3, (‘Hotdog’, ‘Vit_A’): 0, (‘Hotdog’, ‘Dietary_Fiber’): 0, (‘Hotdog’, ‘Carbohydrates’): 18, (‘Hotdog’, ‘Protein’): 10.4}
②创建模型