0
FOODS = {'Beef', 'Chicken'}

# The calories for each food item (a dictionary, where 
# key = food name (string) and value = calories (int)
CALORIES = \
    { 'Beef' : 200,     \
     'Chicken' : 140,   \
    }

class Food():
    __slots__ = (
        'name',         # string name
        'cal'           # Calories
    )

def mkFood( name ):
    result = Food()
    result.name = name
    result.cal = [calories for calories in CALORIES.values()]
    return result

这是计算卡路里目标项目价值的正确方法吗?就像得到 200、140 一样。

试图获得卡路里的价值。就这些。

result.cal = calorie in dict(CALORIES[1])

4

2 回答 2

1

不,正确的方法是:

result.cal = CALORIES[name]
于 2013-11-06T04:02:57.467 回答
0

只需使用dict.values,它会返回字典的所有值:

result.cal = [calories for calories in CALORIES.values()]

这将导致:

>>> print result
[200, 140]

完整代码:

def mkFood( name ):
    """Create and return a newly initialized Food item"""
    result = Food()
    result.cal = [calories for calories in CALORIES.values()]
    return result

希望这可以帮助!

于 2013-11-06T03:55:12.187 回答