网站首页 > 精选文章 正文
Map会将一个函数映射到一个输入列表的所有元素上。这是它的规范:
map(function_to_apply, list_of_inputs)
大多数时候,我们要把列表中所有元素一个个地传递给一个函数,并收集输出。比方说:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map可以让我们用一种简单而漂亮得多的方式来实现。就是这样:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
大多数时候,我们使用匿名函数(lambdas)来配合map。
map还可以用于函数列表。
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
- 上一篇: golang常用数据结构之map详细讲解
- 下一篇: Go 每日一库之 mapstructure
猜你喜欢
- 2024-12-23 JavaScript数组之map、filter、reduce使用详解
- 2024-12-23 通俗易懂的说mapreduce
- 2024-12-23 Javascript中,forEach和map到底有什么区别?
- 2024-12-23 Go 每日一库之 mapstructure
- 2024-12-23 golang常用数据结构之map详细讲解
- 2024-12-23 C++的map用法
- 2024-12-23 java的map是什么_java中的map是什么
- 2024-12-23 java如何对map进行排序详解(map集合的使用)
- 2024-12-23 js 如何定义map及赋值
- 2024-12-23 MapDB
- 最近发表
- 标签列表
-
- 向日葵无法连接服务器 (32)
- git.exe (33)
- vscode更新 (34)
- dev c (33)
- git ignore命令 (32)
- gitlab提交代码步骤 (37)
- java update (36)
- vue debug (34)
- vue blur (32)
- vscode导入vue项目 (33)
- vue chart (32)
- vue cms (32)
- 大雅数据库 (34)
- 技术迭代 (37)
- 同一局域网 (33)
- github拒绝连接 (33)
- vscode php插件 (32)
- vue注释快捷键 (32)
- linux ssr (33)
- 微端服务器 (35)
- 导航猫 (32)
- 获取当前时间年月日 (33)
- stp软件 (33)
- http下载文件 (33)
- linux bt下载 (33)