python3 map函数

本文介绍了Python中map函数的应用,通过实例演示了如何利用自定义函数square处理一系列数字并返回新列表的过程。
map(function, iterable, ...)

iterable可以是一个或多个序列.
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
输入:

def square(x) :            # 计算平方数
    return x ** 2
map(square, [1,2,3,4]) 

输出:

[1, 4, 9, 16]
Python 中,map() 函数是一个用于对可迭代对象中的每个元素应用指定函数的内置函数,返回一个包含函数计算结果的新迭代器。它是 Python 中常见的函数式编程工具之一,能提高代码的简洁性和可读性[^3]。 ### 基本语法 ```python map(function, iterable) ``` - `function`:要应用的函数。 - `iterable`:一个或多个可迭代对象(如列表、元组、字符串等)[^3]。 ### 基本用法示例 #### 示例 1:将列表中的每个元素乘以 2 ```python def multiply_by_two(x): return x * 2 numbers = [1, 2, 3, 4] result = map(multiply_by_two, numbers) print(list(result)) # 输出: [2, 4, 6, 8] ``` #### 示例 2:计算列表中所有元素的绝对值 ```python numbers = [-1, -2, 3, -4] result = map(abs, numbers) print(list(result)) # 输出: [1, 2, 3, 4] ``` ### 与 lambda 表达式结合使用 #### 示例 3:将字符串列表中的每个元素转换为大写 ```python words = ['hello', 'world'] result = map(lambda x: x.upper(), words) print(list(result)) # 输出: ['HELLO', 'WORLD'] ``` #### 示例 4:将字符串中的每个字符转换为大写 ```python string = 'hello' result = map(lambda x: x.upper(), string) print(list(result)) # 输出: ['H', 'E', 'L', 'L', 'O'] ``` ### 处理多个可迭代对象 #### 示例 5:将两个列表中的元素相加 ```python list1 = [1, 2, 3] list2 = [4, 5, 6] result = map(lambda x, y: x + y, list1, list2) print(list(result)) # 输出: [5, 7, 9] ``` #### 示例 6:将三个列表中的元素相加 ```python list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] result = map(lambda x, y, z: x + y + z, list1, list2, list3) print(list(result)) # 输出: [12, 15, 18] ``` ### 异常处理与 map() #### 示例 7:使用 `map()` 和 `try-except` 处理可能的异常 ```python def safe_sqrt(x): try: return x ** 0.5 except ValueError: return None numbers = [-1, 4, 9] result = map(safe_sqrt, numbers) print(list(result)) # 输出: [None, 2.0, 3.0] ``` ### 与其他内置函数的结合 #### 示例 8:结合使用 `map()` 和 `filter()` ```python numbers = [1, 2, 3, 4, 5, 6] even_squares = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)) print(list(even_squares)) # 输出: [4, 16, 36] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值