Python2与Python3的map()

1. map()函数

  • Python2中,map(func, seq1[,seq2[...[,seqn)将func作用于seq*的每个序列的索引相同的元素,并最终生成一个[func(seq1[0], seq2[0],....seqn[0]), func(seq1[1], seq2[1],...seqn[1])...]的列表。但在Python3中,map()函数生成一个map类型的对象。

  Python2中map直接返回作用后的元素的列表

1 >>> a = [1,3,5,7,9]
2 >>> b = [2,4,6,8,0]
3 >>> map(lambda x, y: x+y, a, b)
4 [3, 7, 11, 15, 9]
5 >>> 

  Python3中map返回的则是一个map对象

1 >>> a = [1, 3, 5, 7, 9]
2 >>> b = [2, 4, 6, 8, 0]
3 >>> map(lambda x,y: x + y, a, b)
4 <map object at 0x7f53640e3588>
5 >>> 

  如果想得到列表对象,则还需要调用list转化为列表对象

1 >>> list(map(lambda x,y: x + y, a, b))
2 [3, 7, 11, 15, 9]
3 >>> 
  •  Python2中,map()函数的func可以为None,如map(seq1,seq2[,...[,seqn),其作用类似于将seq*中的对应索引的值取出作为一个元组,最终返回一个包含多个元组的列表。而Python3中,map()函数如果不指定func,则最终对返回的map对象转换时就会抛"TypeError"
1 >>> a = [1, 3, 5, 7, 9]
2 >>> b = [2, 4, 6, 8, 0]
3 >>> list(map(a,b))
4 Traceback (most recent call last):
5   File "<stdin>", line 1, in <module>
6 TypeError: 'list' object is not callable
7 >>> 

  因此,如果map()函数的func参数不指定的话,需要使用zip(seq1, seq2[,...[,seqn)函数代替

出来混,迟早是要还的...
原文地址:https://www.cnblogs.com/blackeyes1023/p/10954243.html