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

Python如何用字典推导式实现big_countries函数筛选符合要求的国家

Python实现big_countries函数的简化方案

你之前尝试字典推导式失败的核心原因是字典推导式中每个唯一键仅会被赋值一次,遍历到同一大洲的第二个符合条件的国家时,会直接覆盖该大洲对应的value值,因此只会保留最后一个匹配的国家。以下是几种可行的简化实现方案:

方案1:使用collections.defaultdict(最简洁易读,性能最优)

仅需一次遍历,代码简洁,可读性最高,生产环境推荐使用该方案:

from collections import defaultdict

def big_countries(country_info: dict) -> dict:
    res = defaultdict(list)
    for country, info in country_info.items():
        if info[4]:
            res[info[0]].append(country)
    return dict(res)

运行后返回结果和预期完全一致:{'Asia': ['Afghanistan'], 'Africa': ['Algeria', 'Angola']}

方案2:纯字典推导式实现(无需额外导入)

如果不想导入任何依赖模块,也可以通过先筛选符合条件的(大洲,国家)元组,再分组聚合的方式写纯原生推导式:

def big_countries(country_info: dict) -> dict:
    # 先筛选出符合条件的(大洲, 国家)元组
    valid_pairs = [(info[0], country) for country, info in country_info.items() if info[4]]
    # 按大洲分组生成结果字典
    return {continent: [c for cont, c in valid_pairs if cont == continent] for continent, _ in valid_pairs}

这种写法完全使用Python原生语法,适合小体量的数据集使用。

方案3:使用itertools.groupby实现

如果你熟悉itertools工具库,也可以用groupby做分组,注意groupby要求同组元素连续,因此需要先对筛选后的元组按大洲排序:

from itertools import groupby

def big_countries(country_info: dict) -> dict:
    valid_pairs = sorted(((info[0], country) for country, info in country_info.items() if info[4]), key=lambda x: x[0])
    return {continent: [item[1] for item in group] for continent, group in groupby(valid_pairs, key=lambda x: x[0])}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:15:01