任何人都可以使用此功能嗎?我沒有線索寫代碼,我在函數體中寫的是錯誤的。鍵入字典:值爲列表
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
感謝您的幫助。由於這是我的第一個計算機科學課程,而且我還沒有學習計數器方法。你認爲你有辦法在沒有櫃檯的情況下解決這個功能嗎?我的教授也希望我返回food_to_quantity。如果我問得太多,我很抱歉。 –
以這種方式使用'sum'是很昂貴的,因爲它使得許多臨時的'Counter'對象僅僅在下一步後丟棄它們('sum'特殊情況[拒絕]'str'以防止相同的低效率,但不能識別它在一般情況下)。重做它爲'dict(counter(x for v in table_to_foods.values()for v in v))',即使是中等大小的輸入,你也會大大減少運行時間(即使是三個密鑰的小字典,每個值使用'sum'的時間是使用帶有genexpr輸入的單個'Counter'的5倍,並且隨着輸入放大,它只會變差。 – ShadowRanger
雖然我不知道@ShadowRanger的方法。感謝你們對我的幫助。 –