# Python map() 函数的功能和用法
# map() 函数会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
# 示例 1: 使用 map() 对列表中的每个元素进行平方运算
numbers = [1, 2, 3, 4, 5]
def square(x):
return x ** 2
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # 输出: [1, 4, 9, 16, 25]
# 示例 2: 使用 map() 和 lambda 表达式将字符串列表转换为大写
words = ["apple", "banana", "cherry"]
upper_words = map(lambda word: word.upper(), words)
print(list(upper_words)) # 输出: ['APPLE', 'BANANA', 'CHERRY']
# 示例 3: 使用 map() 对多个列表进行操作
list1 = [1, 2, 3]
list2 = [4, 5, 6]
def add(x, y):
return x + y
result = map(add, list1, list2)
print(list(result)) # 输出: [5, 7, 9]
下一篇:python逻辑运算符优先级顺序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站