首页 > 其他 > 详细

map函数

时间:2020-06-04 09:03:29      阅读:37      评论:0      收藏:0      [点我收藏+]

描述

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

语法

map() 函数语法:

map(function, iterable, ...)

参数

  • function -- 函数
  • iterable -- 一个或多个序列

 

实例

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

 

上面是一些基础用法,还有更骚的操作

number_str = [‘1‘, ‘2‘, ‘3‘, ‘4‘]
output = [int(e) for e in number_str]
output2 = list(map(int, number_str))
print(number_str)
print(output)
print(output2)

技术分享图片

 

 

 

也可以结合自定义函数使用

***将元组转换成list***
>>> map(int, (1,2,3))
[1, 2, 3]
***将字符串转换成list***
>>> map(int, ‘1234‘)
[1, 2, 3, 4]
***提取字典的key,并将结果存放在一个list中***
>>> map(int, {1:2,2:3,3:4})
[1, 2, 3]
***字符串转换成元组,并将结果以列表的形式返回***
>>> map(tuple, ‘agdf‘)
[(‘a‘,), (‘g‘,), (‘d‘,), (‘f‘,)]
#将小写转成大写
def u_to_l (s):
  return s.upper()
print map(u_to_l,‘asdfd‘)

  

1、对可迭代函数iterable中的每一个元素应用‘function’方法,将结果作为list返回。
来个例子:
>>> def add100(x):
...     return x+100
...
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
就像文档中说的:对hh中的元素做了add100,返回了结果的list。

2、如果给出了额外的可迭代参数,则对每个可迭代参数中的元素‘并行’的应用‘function’。(翻译的不好,这里的关键是‘并行’)
>>> def abc(a, b, c):
...     return a*10000 + b*100 + c
...
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(abc,list1,list2,list3)
[114477, 225588, 336699]
看到并行的效果了吧!在每个list中,取出了下标相同的元素,执行了abc()。

3、如果function给出的是‘None’,自动假定一个‘identity’函数(这个‘identity’不知道怎么解释,看例子吧)
>>> list1 = [11,22,33]
>>> map(None,list1)
[11, 22, 33]
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(None,list1,list2,list3)
[(11, 44, 77), (22, 55, 88), (33, 66, 99)]

 

  

 

 

 

 

map函数

原文:https://www.cnblogs.com/cuc-lyp/p/13041131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!