map()
函数对可迭代对象(如列表、元组等)的每个元素执行给定的函数。
示例
numbers = [1,2,3,4]
# returns the square of a number
def square(number):
return number * number
# apply square() to each item of the numbers list
squared_numbers = map(square, numbers)
# converting to list for printing
result = list(squared_numbers)
print(result)
# Output: [1,4,9,16]
map() 语法
map(function, iterables)
map() 参数
map()
函数接受两个参数
- function - 应用于可迭代对象中每个元素的函数。
- iterables - 可迭代对象,如列表、元组等。
注意:我们可以向 map()
函数传递多个可迭代对象。
map() 返回值
map()
函数返回一个 map 对象,该对象可以轻松地转换为列表、元组等。
示例:map() 的工作原理
def square(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(square, numbers)
print(result)
# converting the map object to set
result = set(result)
print(result)
输出
<map object at 0x7f722da129e8> {16, 1, 4, 9}
在上面的示例中,我们定义了一个名为 numbers 的元组,它有 4 个元素。请注意这一行
result = map(square, numbers)
在这里,map()
函数使用 square
函数对元组的每个元素进行平方运算。初始输出 <map object at 0x7f722da129e8>
表示一个 map 对象。
最后,我们将 map 对象转换为一个集合,并获得元组中每个元素的平方值。
注意:输出是无序的,因为 Python 中的集合是无序集合,不保留元素的原始顺序。
使用 lambda 的 map()
在 map()
函数中,我们也可以使用lambda 函数来代替常规函数。例如,
numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)
print(result)
# convert to set and print it
print(set(result))
输出
<map object at 0x7fc834e22170> {16, 1, 4, 9}
在上面的示例中,我们直接使用 lambda
函数来对元组中的每个元素进行平方运算。
注意:使用 lambda()
函数使代码更简洁、更易读。
使用 map() 和 lambda 添加多个列表
我们可以使用 map()
和 lambda
来在 Python 中添加多个列表。例如,
num1 = [1, 2, 3]
num2 = [10, 20, 40]
# add corresponding items from the num1 and num2 lists
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))
输出
[11, 22, 43]
在上面的示例中,我们向 map()
函数传递了两个列表 num1
和 num2
。请注意这一行,
result = map(lambda n1, n2: n1+n2, num1, num2)
在这里,lambda
函数在 map()
中用于将两个列表的对应元素相加。
使用 map() 修改字符串
我们可以使用 map()
函数来修改字符串。例如,
# list of actions
actions=['eat', 'sleep','read']
# convert each string into list of individual characters
result= list(map(list,actions))
print(result)
输出
[['e', 'a', 't'], ['s', 'l', 'e', 'e', 'p'], ['r', 'e', 'a', 'd']]
在上面的示例中,我们在 map()
外层使用了 list(),将每个字符串转换为单个字符的列表。
另请阅读