【发布时间】:2021-12-19 05:58:48
【问题描述】:
我不会进一步解释,而是首先提供一些我的代码的上下文,这些代码有效但似乎效率很低:
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}
>>> get_quantities({'t1': ['pie'],
't2': ['orange pie'], 't3': ['pie']})
{'pie': 2, 'orange pie': 1}
"""
food_to_quantity = {}
# Accumulate the food information here.
# Creating a dictionary with the new keys as values from the other
for j in table_to_foods.values():
for a in j:
food_to_quantity[a] = 0
# Increment based on number of occurrences
for j in table_to_foods.values():
for a in j:
food_to_quantity[a] += 1
return food_to_quantity
必须有一种更简单的方法来创建一个新字典,其中 table_to_foods 的值作为键,任何食物值的出现次数作为值。
【问题讨论】:
标签: python list dictionary accumulate