任何人都可以使用此功能吗?我没有线索写代码,我在函数体中写的是错误的。键入字典:值为列表
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的方法。感谢你们对我的帮助。 –