python map函数
文章目录
在Python中,
map()
函数用于将一个函数应用于可迭代对象(如列表或元组)中的每个元素,并返回一个包含结果的新的可迭代对象。
map()
函数的语法如下:
map(function, iterable)
其中,function
是要应用的函数,iterable
是可迭代对象,如列表、元组等。
以下是map()
函数的示例用法:
# 示例1:将列表中的每个元素都平方
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
# 输出: [1, 4, 9, 16, 25]
# 示例2:将字符串列表中的每个字符串转换为大写
words = ['apple', 'banana', 'cherry']
uppercase_words = list(map(str.upper, words))
print(uppercase_words)
# 输出: ['APPLE', 'BANANA', 'CHERRY']
在示例1中,我们使用map()
函数将列表numbers
中的每个元素都平方,并将结果存储在squared_numbers
列表中。在示例2中,我们使用map()
函数将字符串列表words
中的每个字符串都转换为大写,并将结果存储在uppercase_words
列表中。
需要注意的是,map()
函数返回的是一个迭代器对象,如果需要得到一个列表或其他类型的可迭代对象,可以使用list()
函数将其转换为相应的类型。