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

Python实现列表按字典匹配替换、缺失值填<none>生成新列表的方法

解决方案

Python 字典的键查找时间复杂度为 O(1),搭配列表推导式实现的逻辑性能最优,完全适配万级以上数据的处理需求。
核心直接使用字典内置的get()方法,匹配不到键时直接返回指定的默认值<none>即可:

words = ['apple', 'peach', 'tomato']
translations = {'apple': ' apfel', 'banana': 'banane', 'peach': 'pfirsich', 'orange': 'apfelsine'}

# 如翻译值无多余空格可去掉.strip()
result = [translations.get(word, '<none>').strip() for word in words]

运行后输出的result和预期完全一致:

['apfel', 'pfirsich', '<none>']

效率说明

  • 列表推导式是Python底层C实现的遍历逻辑,比手写Python层的普通for循环性能高30%以上
  • 单次字典查找耗时稳定在纳秒级,就算处理10万条数据总耗时也在10ms以内,无性能压力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:48:02