gpt4 book ai didi

python - 输入字典 : values that are lists

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:19 25 4
gpt4 key购买 nike

谁能帮我实现这个功能?我不知道写代码,我在函数体中写的是错误的。

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 - 输入字典 : values that are lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47106751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com