网站首页 > 技术文章 正文
map()是Python中的内置函数,可将函数应用于给定可迭代对象中的所有元素。 它允许您编写简单干净的代码而无需使用循环
Python map()函数
map()函数采用以下形式:
map(function, iterable, ...)
它接受两个强制性参数:
function-为每个iterable元素调用的函数。
iterable-一个或多个支持迭代的对象。 Python中的大多数内置对象(如列表,字典和元组)都是可迭代的。
在Python 3中,map()返回大小等于传递的可迭代对象的map对象。 在python 2中,该函数返回一个列表。
让我们看一个示例,以更好地解释map()函数的工作方式。 假设我们有一个字符串列表,我们希望将列表中的每个元素都转换为大写。
一种方法是使用传统的for循环:
directions = ["north", "east", "south", "west"]
directions_upper = []
for direction in directions:
d = direction.upper()
directions_upper.append(d)
print(directions_upper)
输出
['NORTH', 'EAST', 'SOUTH', 'WEST']
使用map()函数,代码将更加简单和灵活。
directions = ["north", "east", "south", "west"]
directions_upper = map(lambda s: s.upper(), directions)
print(list(directions_upper))
我们使用list()函数将返回的地图对象转换为列表:
输出
['NORTH', 'EAST', 'SOUTH', 'WEST']
如果回调函数很简单,那么更多的Python方式是使用lambda函数:
directions = ["north", "east", "south", "west"]
directions_upper = map(lambda s: s.upper(), directions)
print(list(directions_upper))
A lambda function is a small anonymous function.
这是另一个示例,显示了如何创建从1到10的平方数的列表:
squares = map(lambda n: n*n , range(1, 11))
print(list(squares))
输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The range() function generates a sequence of integers.
将map()与多个Iterables一起使用
您可以根据需要将尽可能多的可迭代对象传递给map()函数。 回调函数接受的必需输入参数的数量必须与可迭代的数量相同。
下面的示例显示如何在两个列表上执行逐元素乘法:
def multiply(x, y):
return x * y
a = [1, 4, 6]
b = [2, 3, 5]
result = map(multiply, a, b)
print(list(result))
输出
[2, 12, 30]
相同的代码,但使用lambda函数的外观如下:
a = [1, 4, 6]
b = [2, 3, 5]
result = map(lambda x, y: x*y, a, b)
print(list(result))
当提供多个可迭代时,返回的对象的大小等于最短的可迭代。
让我们看一个示例,其中可迭代项的长度不同:
a = [1, 4, 6]
b = [2, 3, 5, 7, 8]
result = map(lambda x, y: x*y, a, b)
print(list(result))
输出
[2, 12, 30]
结论:
Python的map()函数采用一个可迭代的对象以及一个函数,并将该函数应用于可迭代的每个元素。
猜你喜欢
- 2024-10-18 【Python】map函数的常见用法,你知道多少?
- 2024-10-18 Python 中的数据可视化:将列表转换为图形
- 2024-10-18 Java 把一个 List 转换为字符串(java list转成字符串)
- 2024-10-18 Java Stream API:将线性集合添加到Map,键为对象属性
- 2024-10-18 SpringBoot读取配置文件中的数据到map和list
- 2024-10-18 「Java」咦,它就是Map和List的儿子吧
- 2024-10-18 一日一技:举例说明python中的map()方法
- 2024-10-18 详解 Python Map 函数(python map函数的用法)
- 2024-10-18 你应该知道的Java Map 的七个常见问题!
- 2024-10-18 Java核心数据结构(List、Map、Set)原理与使用技巧
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- windowsscripthost (67)
- apt-getinstall-y (86)
- node_modules怎么生成 (76)
- chromepost (65)
- c++int转char (75)
- static函数和普通函数 (76)
- el-date-picker开始日期早于结束日期 (70)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- js数组插入 (83)
- linux删除一个文件夹 (65)
- mac安装java (72)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)