Python内置函数_map函数

1. 概念

1.1 描述

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

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

1.2 语法

map(function, iterable, ...)

参数说明

  1. function:函数
  2. iterable:一个或多个序列/可迭代对象

源码内容

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.
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

1.3 返回值

  • py2.X 返回列表
  • py3.X 返回迭代器

2. 实例

# 1.计算列表里所有元素的平方
def square(x):
    return x**2

ret01 = map(square,[1,2,3])
print(ret01)    # <map object at 0x102f3fcf8> ;py3.x返回迭代器
for i in ret01:
    print(i)
'''
1
4
9
'''

# 2.lambda函数实现以上功能
ret02 = map(lambda x:x**2,[1,2,3])
lst02 = [i for i in ret02]    # 通过列表推导式
print(lst02)  # [1, 4, 9]


# 3.参数中多个迭代器的情况
ret03 = map(lambda x,y:x+y,[1,2,3],[2,3,4])
lst03 = [item for item in ret03]
print(lst03)    # [3, 5, 7]


# 3.多个迭代器中元素个数不同时
# 会从左到右,以最短为准,取完为止
ret04 = map(lambda x,y:x+y,[2,3,4],[2,3,4,5])
lst04 = [item for item in ret04]
print(lst04)    # [4, 6, 8]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值