# 使用map函数将列表中的每个元素平方
# 定义一个函数,用于计算平方
def square(num):
return num ** 2
# 原始列表
numbers = [1, 2, 3, 4, 5]
# 使用map函数将列表中的每个元素平方
squared_numbers = map(square, numbers)
# 将map对象转换为列表并打印结果
print(list(squared_numbers)) # 输出: [1, 4, 9, 16, 25]
# 也可以使用lambda表达式来简化代码
squared_numbers_lambda = map(lambda x: x ** 2, numbers)
# 将map对象转换为列表并打印结果
print(list(squared_numbers_lambda)) # 输出: [1, 4, 9, 16, 25]
map 函数会根据提供的函数对指定序列做映射。map 会将可迭代对象中的每一个元素应用到给定的函数上,并返回一个新的迭代器。square 函数,它接收一个数字并返回它的平方。然后我们使用 map 函数将这个操作应用到 numbers 列表中的每一个元素上。lambda 表达式来简化代码,直接在 map 中定义匿名函数。上一篇:python心形代码
下一篇:zip函数python作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站