Python map函数的用法和实例
在Python中,map() 函数是一种内置函数,用于对指定序列中的所有元素执行函数。它返回一个迭代器,该迭代器生成由应用于输入序列的函数处理的结果的序列。
语法
map() 函数的语法如下:
map(function, iterable, ...)
参数说明:
- function: 对每个可迭代输入序列中的每个元素执行的函数
- iterable: 一个或多个序列
示例
将列表中的每个元素平方
def square(x):
return x ** 2
nums = [1, 2, 3, 4, 5]
squared_nums = map(square, nums)
print(list(squared_nums))
输出为:
[1, 4, 9, 16, 25]
将两个列表中的元素相加
def add(x, y):
return x + y
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
sum_list = map(add, list1, list2)
print(list(sum_list))
输出为:
[6, 6, 6, 6, 6]
将字符串列表中的元素转换为大写
words = ['hello', 'world', 'python']
upper_words = map(str.upper, words)
print(list(upper_words))
输出为:
['HELLO', 'WORLD', 'PYTHON']
注意事项
- map() 函数返回的是一个迭代器对象,需要使用 list() 函数将其转换为列表
- 输入的函数可以是内置函数、自定义函数或 lambda 函数
通过这些示例,我们可以看到 map() 函数的强大之处,它可以简化对序列中元素的处理和转换,提高代码的可读性和效率。