"""
模块:python3 map().py
功能:
参考:https://www.runoob.com/python/python-func-map.html
知识点:
1.map(function, iterable, ...) Python 内置函数
map() 会根据提供的函数 对 指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,
返回包含每次 function 函数返回值的新列表。
function -- 函数
iterable -- 一个或多个序列
Python 3.x 返回迭代器。
"""
# 1.求两个列表对应数值的差。
list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 11]
def minus(x, y):
"""
功能:求 x 和 y 的差。
:param x: 减数
:param y: 被减数
:return: x - y
"""
return x - y
print(list(map(minus, list1, list2)))
# [-1, -1, -1, -1, -2]
print(list(map(lambda x, y: x - y, list1, list2)))
# [-1, -1, -1, -1, -2]
# 2.
print("2:")
def square(x): # 计算平方数
"""
功能:求 x 的平方。
:param x:
:return:
"""
return x ** 2
# 计算列表各个元素的平方
print(list(map(square, [1, 2, 3, 4, 5])))
# [1, 4, 9, 16, 25]
# 使用 lambda 匿名函数
print(list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])))
# [1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
print(list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])))
# [3, 7, 11, 15, 19]
来源:CSDN
作者:学无止境慢慢来
链接:https://blog.csdn.net/weixin_42193179/article/details/104286471