我很乐意在我的python课程中为以下问题提供帮助
您想算一下篮子里的水果数。为此,您需要以下词典和水果清单。使用字典和列表来计算水果总数,但是您不想计算篮子中的其他项目。
我试图使用两个for循环来解决问题:
result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for fruit in fruits:
for key, value in basket_items.items():
result+=1
else: result+=0
print(result)
我的代码为24,但正确的答案为23
答案 0 :(得分:1)
使用dict.get
例如:
result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for fruit in fruits: #Iterate each element in list
result += basket_items.get(fruit, 0) #Add to result.
print(result) # --> 23
答案 1 :(得分:0)
另一个选择可能是:
result = 0
for key, value in basket_items.items():
if key in fruits:
result += value
答案 2 :(得分:0)
result = 0
basket_items = {'apples': 4, 'oranges': 19, 'kites': 3, 'sandwiches': 8}
fruits = ['apples', 'oranges', 'pears', 'peaches', 'grapes', 'bananas']
for key, value in basket_items.items():
if key in fruits:
result+= value