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

Python中如何使用map与set并优化列表转小写去重的冗余代码

代码优化方案

原代码存在冗余的类型转换操作,且map+lambda的写法可读性不高,可按以下方式优化:

基础优化版(功能与原代码完全一致)

去掉多余的内层list()转换:set()本身支持直接接收可迭代对象,不需要先把map的输出结果转成列表,优化后代码:

exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  # example list
x = list(set(map(lambda x: x.lower(), exclusion_new)))
print(x)
# 输出:['abs', 'acd', 'bde', 'kji'] (顺序不固定)

更易读的Pythonic写法

用生成器表达式替代map+lambda,语法更直观,新手更容易理解:

exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  # example list
x = list(set(s.lower() for s in exclusion_new))
print(x)

保留元素出现顺序的版本

如果你需要保留原列表中元素第一次出现的顺序(set本身是无序的,输出顺序不固定),Python 3.7+可使用dict.fromkeys实现有序去重:

exclusion_new = ["Abs", "acd", "bde", "Abs", "Kji"]  # example list
x = list(dict.fromkeys(s.lower() for s in exclusion_new))
print(x)
# 输出固定为:['abs', 'acd', 'bde', 'kji']

内容的提问来源于stack exchange,提问作者Luís Henrique Martins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:39:03