**

python中map()函数总结

**

1.关于map()函数

(1)map函数是python中的一个内置函数,做映射。
(2)map()函数返回的是一个新的迭代器对象,不会改变原有对象!

2.语法

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

简单理解:

map(function, iterable)
#function -- 函数
#iterable -- 序列

其实map()的作用很简单,只需要记住一句话:将函数映射作用于序列上!!

3.示例

(1)利用map()结合split()进行输入
①输入str:a,b,c = input().split()
②输入整数:a,b,c = map(int,input().split())
③输入浮点数:a,b,c = map(float,input().split())

a,b,c = map(int,input().split(","))#此处function为int,序列即输入
print(a,b,c)
>>>1,2,3
>>>1 2 3

(2)map()返回迭代器

l = [2,0,0,2,0,2,2,2]
result = map(lambda x: x*x,l)
print(result)#返回一个迭代器
>>><map object at 0x000001DC51E22EC8>
print(list(result))#使用 list() 转换为列表
>>>[4, 0, 0, 4, 0, 4, 4, 4]
print(list(map(lambda x:x*x,l)))#合并为一行代码解决
>>>[4, 0, 0, 4, 0, 4, 4, 4]

注:map函数会返回一个迭代器,常使用 list() 来转换。

浅浅记录一个小错误(代码如下):

list = [2,0,0,2,0,2,2,2]
result = map(lambda x: x*x,list)
print(result)
print(list(result))

结果报错:

TypeError: 'list' object is not callable

揭秘我之前从没注意过这个问题! ):

我试图将map()返回的结果转换为列表list,但是由于变量list和函数list重名了,所以函数在使用list函数时,发现list是一个定义好的列表,而列表是不能被调用的,因此抛出一个类型错误。
(3)map中的function取自定义函数

def function(x):
    return x*2
print(list(map(function,range(3))))
>>>[0, 2, 4]

(4)迭代器仅一次访问

l = ['1', '2', '3', '4', '5', '6']
print(l)
>>>['1', '2', '3', '4', '5', '6']
l_int = map(lambda x: int(x), l)
for i in l_int:
    print(i, end=' ')
>>>1 2 3 4 5 6 
print()
print(list(l_int))
>>>[]#由于map()生成的是迭代器,所以for循环以后再使用l_int时迭代器中的数据已经为空了!!!
物联沃分享整理
物联沃-IOTWORD物联网 » python中map()函数总结

发表评论