欢迎访问宙启技术站
智能推送

使用Python的map()函数进行序列操作的实例

发布时间:2024-01-06 16:52:19

Python的map()函数是一个内建函数,用于对序列(如列表、元组等)中的每个元素执行相同的操作。它接受两个参数:一个是函数或映射,另一个是序列。它将函数应用于序列中的每个元素,并返回一个生成器对象,该对象包含了对原始序列中的每个元素应用函数后的结果。

下面是使用Python的map()函数进行序列操作的一些示例:

示例1: 将列表中的每个元素加1

def add_one(x):
    return x + 1

nums = [1, 2, 3, 4, 5]
result = map(add_one, nums)
print(list(result))  # 输出:[2, 3, 4, 5, 6]

示例2:计算列表中每个元素的平方

def square(x):
    return x**2

nums = [1, 2, 3, 4, 5]
result = map(square, nums)
print(list(result))  # 输出:[1, 4, 9, 16, 25]

示例3:将字符串列表中的每个元素转换为大写

words = ["hello", "world", "python"]
result = map(str.upper, words)
print(list(result))  # 输出:['HELLO', 'WORLD', 'PYTHON']

示例4:使用lambda函数对列表中的每个元素做加法计算

nums1 = [1, 2, 3, 4, 5]
nums2 = [10, 20, 30, 40, 50]
result = map(lambda x, y: x + y, nums1, nums2)
print(list(result))  # 输出:[11, 22, 33, 44, 55]

示例5:给定两个列表,对应位置的元素相乘

nums1 = [1, 2, 3, 4, 5]
nums2 = [10, 20, 30, 40, 50]
result = map(lambda x, y: x * y, nums1, nums2)
print(list(result))  # 输出:[10, 40, 90, 160, 250]

示例6:将元组中的每个元素取反

def negate(x):
    return -x

nums = (1, -2, 3, -4, 5)
result = map(negate, nums)
print(tuple(result))  # 输出:[-1, 2, -3, 4, -5]

示例7:将字符串列表中的每个元素转换为其长度

words = ["apple", "banana", "cherry"]
result = map(len, words)
print(list(result))  # 输出:[5, 6, 6]

以上是使用Python的map()函数进行序列操作的一些实例。通过map()函数,我们可以非常方便地对序列中的每个元素进行相同的操作,并获得操作后的结果序列。