zoukankan      html  css  js  c++  java
  • 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)函数代替

    出来混,迟早是要还的...
  • 相关阅读:
    1334: 好老师
    poj 2255 Tree Recovery
    2006浙大:简单计算器
    POJ1001(C++处理大数)
    HDU2159(二维完全背包)
    POJ2080:Calendar(计算日期)
    2008上交:Day of Week
    POJ1365:质因数分解
    VIJOS:P1706(舞会)
    POJ2449:K短路
  • 原文地址:https://www.cnblogs.com/blackeyes1023/p/10954243.html
Copyright © 2011-2022 走看看