# 使用map函数将列表中的每个元素平方
def square(num):
return num ** 2
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
# 将map对象转换为列表以查看结果
squared_numbers_list = list(squared_numbers)
print(squared_numbers_list) # 输出: [1, 4, 9, 16, 25]
# 使用lambda表达式简化代码
squared_numbers_lambda = map(lambda x: x ** 2, numbers)
print(list(squared_numbers_lambda)) # 输出: [1, 4, 9, 16, 25]
# 使用map处理多个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
summed_list = map(lambda x, y: x + y, list1, list2)
print(list(summed_list)) # 输出: [5, 7, 9]
map(function, iterable) 是 Python 内置函数,它会根据提供的函数对指定的序列(如列表)进行映射。function 参数是一个函数,iterable 参数是一个或多个可迭代对象(如列表、元组等)。map 返回一个迭代器,可以通过 list() 函数将其转换为列表。square 函数,并使用 map 将其应用于 numbers 列表中的每个元素。lambda 表达式来简化代码。map 处理多个列表,并对它们的对应元素进行操作。上一篇:python向下取整数的函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站