[英]Type dict: values that are lists
誰能幫我這個功能? 我沒有編寫代碼的線索,我在函數體內編寫的內容是錯誤的。
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
如果您喜歡使用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}
在沒有庫的情況下對項目進行計數的常見方法是使用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}
使用Counter
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))
您可能不必從Counter
dict
( Counter
是dict
的子類),但是我在這里這樣做,因此您的類型相同
嘗試這個:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.