惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
云风的 BLOG
云风的 BLOG
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Announcements
Recent Announcements
IT之家
IT之家
Google DeepMind News
Google DeepMind News
罗磊的独立博客
爱范儿
爱范儿
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
U
Unit 42
MongoDB | Blog
MongoDB | Blog
S
SegmentFault 最新的问题
B
Blog
博客园 - 叶小钗
月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
V
Visual Studio Blog
C
Check Point Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

博客园 - npe0

策略模式在项目中的应用 博文阅读密码验证 - 博客园 MyBatis-Plus 的动态SQL片段用法 EasyExcel的多级表头 docker镜像搬运命令 macbook绕过安全控制安装第三方软件 阿里通义千问大模型初探 java.io.IOException: Cannot run program “az”: CreateProcess error=2, 系统找不到指定的文件。 Git使用问题记录 seata的分布式事务处理机制 JVM常用命令 你可能不知道的Collectors用法 easyexcel导出Bigdecimal数据格式问题 百万千万级Excel导出 arthas 常用命令 对find,xargs,grep和管道的一些深入理解 PlantUML 分库分表 jvm优化
Python中使用列表、map和filter函数配合lambda表达式来操作集合
npe0 · 2025-09-19 · via 博客园 - npe0

在 Python 中,map()filter()lambda 表达式是处理集合(如列表)的常用工具,可以快速实现 转换过滤 操作。以下是具体示例:


1. map() 函数:对列表元素进行转换

作用

对列表的每个元素应用一个函数,返回转换后的元素组成的迭代器。

语法

map(function, iterable)

示例

# 示例1:计算列表中每个数的平方
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # 输出:[1, 4, 9, 16, 25]

# 示例2:将字符串列表转为大写
names = ["alice", "bob", "charlie"]
upper_names = list(map(lambda s: s.upper(), names))
print(upper_names)  # 输出:['ALICE', 'BOB', 'CHARLIE']

2. filter() 函数:过滤列表元素

作用

筛选列表中满足条件的元素,返回符合条件的迭代器。

语法

filter(function, iterable)

示例

# 示例1:过滤出偶数
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出:[2, 4]

# 示例2:过滤出长度大于3的字符串
words = ["a", "ab", "abc", "abcd"]
long_words = list(filter(lambda s: len(s) > 3, words))
print(long_words)  # 输出:['abcd']

3. map()filter() 联合使用

示例:先过滤偶数,再计算平方

numbers = [1, 2, 3, 4, 5]
# 先过滤偶数,再计算平方
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result)  # 输出:[4, 16]

等价的列表推导式

result = [x ** 2 for x in numbers if x % 2 == 0]

4. 更复杂的操作示例

场景:对字符串列表进行清洗(过滤空字符串并转为大写)

strings = ["hello", "", "world", "   ", "python"]
# 过滤空字符串和仅含空格的字符串,转为大写
clean_strings = list(map(
    lambda s: s.upper(),
    filter(lambda s: s.strip() != "", strings)
))
print(clean_strings)  # 输出:['HELLO', 'WORLD', 'PYTHON']

5. lambda 表达式的作用

lambda 是匿名函数的快捷写法,适用于简单操作:

# 等价于:
def square(x):
    return x ** 2

# lambda 写法:
lambda x: x ** 2

关键区别

函数 用途 返回值类型 示例
map() 转换元素 迭代器 map(lambda x: x*2, [1,2,3])
filter() 过滤元素 迭代器 filter(lambda x: x>2, [1,2,3])

常见错误与解决方案

错误1:忘记转换为列表

# ❌ 错误写法:直接打印迭代器
numbers = [1, 2, 3]
print(map(lambda x: x + 1, numbers))  # 输出:<map object at 0x...>

正确写法

print(list(map(lambda x: x + 1, numbers)))  # 输出:[2, 3, 4]

错误2:lambda 参数不匹配

# ❌ 错误写法:lambda 需要一个参数,但传递了多个
print(list(map(lambda x, y: x + y, [1,2], [3,4])))  # 输出:[4, 6]
# 如果仅使用一个 lambda 参数会报错:
# print(list(map(lambda x: x + y, [1,2], [3,4])))  # NameError: name 'y' is not defined

正确写法

# 如果需要多个参数,确保 lambda 定义多个参数
print(list(map(lambda x, y: x + y, [1,2], [3,4])))  # 输出:[4, 6]

进阶示例

场景:统计列表中字符串的长度,并过滤出长度为偶数的项

words = ["apple", "banana", "cherry", "date"]
# 先计算长度,再过滤偶数长度
result = list(map(
    lambda length: length,
    filter(lambda l: l % 2 == 0, map(len, words))
))
print(result)  # 输出:[5, 6] ("banana" 长度6,"date" 长度4 → 过滤后为 5? 需检查)


实际输出需根据具体条件调整。例如,len("apple")=5 是奇数会被过滤,而 "banana" 长度6是偶数会被保留。


最佳实践

  1. 优先使用列表推导式

    # 替代 map 和 filter 的列表推导式
    squares = [x ** 2 for x in numbers if x % 2 == 0]
    
  2. 复杂逻辑避免过度嵌套
    对于复杂操作,建议定义命名函数而非复杂的 lambda

    def is_even(x):
        return x % 2 == 0
    
    def square(x):
        return x ** 2
    
    result = list(map(square, filter(is_even, numbers)))
    

总结

需求 map 用法 filter 用法
转换元素(如平方) map(lambda x: x**2, numbers) 不适用
过滤元素(如保留偶数) 不适用 filter(lambda x: x%2==0, numbers)
组合操作 map(..., filter(..., list)) filter(..., map(..., list))

通过 mapfilter 结合 lambda,可以高效简洁地处理列表,但 列表推导式 通常更易读且性能更好。