You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何更简洁实现以原字典值元素为新键、元素出现次数为值的统计功能

优化实现方案

原有代码通过两次嵌套遍历完成统计,时间复杂度为O(2n)(n为所有餐品总数量),可以简化为单次遍历,也可以用Python标准库实现更简洁高效的逻辑。

方案1:原生Python实现(无额外依赖)

仅通过一次嵌套遍历完成统计,用字典get方法处理键不存在的默认值,无需提前初始化所有餐品的计数:

from typing import Dict, List

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}    

    >>> get_quantities({'t1': ['pie'],
    't2': ['orange pie'], 't3': ['pie']})

    {'pie': 2, 'orange pie': 1} 
    """
    food_to_quantity = {}
    for foods in table_to_foods.values():
        for food in foods:
            food_to_quantity[food] = food_to_quantity.get(food, 0) + 1
    return food_to_quantity

方案2:标准库collections.Counter实现(最简洁高效)

Counter是Python标准库专门用于计数的工具,底层为C实现,比手动写Python循环效率更高,仅需一行核心代码即可完成统计:

from typing import Dict, List
from collections import Counter

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}    

    >>> get_quantities({'t1': ['pie'],
    't2': ['orange pie'], 't3': ['pie']})

    {'pie': 2, 'orange pie': 1} 
    """
    return dict(Counter(food for foods in table_to_foods.values() for food in foods))

如果允许返回Counter类型(Counter是dict的子类,支持所有字典操作),可以去掉外层的dict()转换。


内容的提问来源于stack exchange,提问作者Curulian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:18:01