recipe = [
['eggs', 'flour', 'meat'],
[4, 250, 5],
['large','grams', 'kg'],
]
如果你想将数量除以二,并改变你存储的内容,把它放在一边作为字典会好得多:
for quantity, index in enumerate(recipe[1])
recipe[1][index] = quantity/2
更好的方法是使用字典,它允许您为数据项命名:
recipe = {"eggs":{"quantity":4, "measurement":"large"},
"flour":{"quantity":250,"measurement":"grams"},
"meat":{"quantity":5,"measurement":"kg"}}
现在除以二变成:
for ingredient in recipe:
recipe[ingredient]["quantity"] = recipe[ingredient]["quantity"]/2
并打印配方变为:
for ingredient in recipe:
print "{} {} {}".format(recipe[ingredient]["quantity"], recipe[ingredient]["measurement"], ingredient)
这会生成:
4 large eggs
250 grams flour
5 kg meat
并且不关心索引号等。