假设像这样的字典:
fruit_stand = {
"Lemon": [(Yellow, 5, 2.99)],
"Apple": [(Red, 10, 0.99), (Green, 9, 0.69)],
"Cherry": [(White, 2, 5.99),(Red, 5, 5.99)]
}
您实际上可以遍历字典以获取其键:
for fruit_name in fruit_stand:
print fruit_name
# Lemon
# Apple
# Cherry
# NOTE: Order not guaranteed
# Cherry, Lemon, Apple are equally likely
然后,您可以使用字典的方法来获取,items对的元组(您称之为“括号”):keyvalue
for fruit_name, fruits in fruit_stand.items():
print fruit_name, "=>", fruits
# Lemon => [(Yellow, 5, 2.99)]
# Apple => [(Red, 10, 0.99), (Green, 9, 0.69)]
# Cherry => [(White, 2, 5.99),(Red, 5, 5.99)]
lists (即括号内的[])也是可迭代的:
for fruit in [(White, 2, 5.99),(Red, 5, 5.99)]:
print fruit
# (White, 2, 5.99)
# (Red, 5, 5.99)
所以我们可以使用每个fruits列表来访问我们的tuple:
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for fruit in fruit_list:
print fruit
正如我们所见,items我们可以将元组解包为多个值:
x, y = (1, 2)
print x
print y
# 1
# 2
所以我们可以将每一个解压fruit成它的组成部分:
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for color, quantity, cost in fruit_list:
print color, quantity, cost
然后得到总数并不难:
# We need to store our value somewhere
total_value = 0
for fruit_name, fruit_list in fruit_stand.items():
# Ignore fruit_name and iterate over the fruits in fruit_list
for color, quantity, cost in fruit_list:
total_value += (quantity * cost)
print total_value
话虽如此,有更清晰的做事方式:
您可以使用列表推导来简化for循环:
for fruit_name in fruit_stand
operation(fruit_name)
可以翻译成这个列表理解:
[operation(fruit_name) for fruit_name in fruit_stand]
因此,我们可以将嵌套for循环翻译成:
sum([cost * quantity \ # Final operation goes in front
for _, fruits in fruit_stand.items() \
for _, cost, quantity in fruits])
因为我们实际上并不需要列表,所以我们可以摆脱它,Python 将为我们创建一个生成器:
sum(cost * quantity \ # Note the missing []
for _, fruits in fruit_stand.items() \
for _, cost, quantity in fruits)
您可以添加一个__add__方法,Fruit以便将两组水果加在一起给出两组的总成本Fruit(但您可能希望创建一个中间数据结构来做到这一点,也就是说Basket不必Fruit担心quantity哪个不'不真正属于Fruit,除非 的任何实例Fruit具有内在数量 1。我省略了此选项的代码,因为此答案已经太长了。