map函数

描述

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)]

 

  

 

 

 

 


posted @ 2020-06-04 01:24  浅尝辄止的游离  阅读(1580)  评论(0编辑  收藏  举报