谁能帮我实现这个功能吗?我不知道如何编写代码,并且我在函数体中编写的内容是错误的。
def get_quantities(table_to_foods: Dict[str, List[str]]) -> Dict[str, int]:
"""The table_to_foods dict has table names as keys (e.g., 't1', 't2', and
so on) and each value is a list of foods ordered for that table.
Return a dictionary where each key is a food from table_to_foods and each
value is the quantity of that food that was ordered.
>>> get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'],
't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})
{'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3}
"""
food_to_quantity = {}
for t in table_to_foods:
for i in table_to_foods[t]:
if i in table_to_foods[t]:
food_to_quantity[i] = food_to_quantity[i] + 1
return food_to_quantity
Run Code Online (Sandbox Code Playgroud)
itertools.chain如果您喜欢使用and ,这只是另一种方法collections.Counter:
from itertools import chain
from collections import Counter
dict(Counter(chain.from_iterable(foods.values())))
#or Simply
dict(Counter(chain(*foods.values())))
#Output:
#{'apple': 3, 'banana': 4, 'grapes': 1, 'orange': 1}
Run Code Online (Sandbox Code Playgroud)