任何人都可以帮我这个功能吗?我不知道编写代码,我在函数体中编写的内容是错误的。
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
答案 0 :(得分:4)
如果您喜欢使用itertools.chain
和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}
答案 1 :(得分:2)
计算没有库的项目的常用方法是使用python get()
函数
foods = {
't1': ['banana', 'apple', 'banana'],
't2': ['orange', 'apple', 'banana'],
't3': ['apple', 'grapes', 'banana']
}
def get_quantities(foodLists):
totals = {}
for foodList in foodLists.values():
for food in foodList:
totals[food] = totals.get(food, 0) + 1
return totals
print(get_quantities(foods))
打印哪些:
{'banana': 4, 'apple': 3, 'orange': 1, 'grapes': 1}
答案 2 :(得分:1)
使用Counter
s
from collections import Counter
def get_quantities(table_to_foods: Dict[str, List[str]]) -> Dict[str, int]:
return dict(Counter(x for v in table_to_foods.values() for x in v))
您可能不需要dict
Counter
Counter
是dict
的子类,但是我这样做,所以你的类型是相同
答案 3 :(得分:0)
试试这个:
def get_quantities(table_to_foods):
food_to_quantity = {}
for table in table_to_foods.values():
for food in table:
food_to_quantity[food] = food_to_quantity.get(food, 0) + 1
return food_to_quantity
您可以使用.values()来获取字典中的值,然后遍历每个项目。如果食物在字典中,则在其值中加1,如果没有,则将食物添加为字典中的新项目。
get_quantities({
't1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'],
't2': ['Steak pie', 'Poutine', 'Vegetarian stew'],
't3': ['Steak pie', 'Steak pie']
})
如果打印,应输出以下内容:
{'Poutine': 2, 'Steak pie': 3, 'Vegetarian stew': 3}
有关词典的更多信息: https://docs.python.org/3/tutorial/datastructures.html#dictionaries