map函数用法

话不多说,对于一个新的内置函数,不会用的情况,我都会先用help查看一下map的用法。

print(help(map))
"""
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).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
"""

大致来说,map返回的是一个对象,其中参数func代表的函数(也可以是python内置的函数),*iterables则是一个对象,输出的(显示的)就是一个map对象

example:

# 插入内置函数(str--转换数据类型),float,int,tuple等等均可以
n1 = [1,2,3]
n2 = (1,2,3)
n3 = "1,2,3"
print(list(map(float,n1)))  # [1.0, 2.0, 3.0]
# 其中float为python内置函数,进行数据类型转换的,n1(list数据类型)则是操作的对象。
print(list(map(str,n1)))    # ['1', '2', '3']
print(tuple(map(str,n2)))   # ('1', '2', '3')
print(list(map(str,n3)))    # ['1', ',', '2', ',', '3']
print(str(map(str,n3)))     # <map object at 0x0000026A1D204B38>

说一点。字符串类型(str)的数据外面套上map函数,可以将里面的任何字符变成一个个列表的元素。

另一点插入自定义函数:

def p(x):
    return x+10
n = [1,2,3]
q = map(p,n)
print(list(q))      # [11, 12, 13]
print(tuple(q))     # ()
print(str(q))       # <map object at 0x0000026A1CF78128>

自定义了一个函数,每一项都将列表的每一项都加10,再用map函数调用,传入自定义函数和列表的元素。输出结果如上!

最后一点,*iterables假如传入多个值呢?例子如下:

def add(x,y):
    return x+y
x1 = [1,2,3]
x2 = [4,5,6]
x3 = [1,3]
r = map(add,x1,x2)
print(r)        # <map object at 0x0000023C38DA4C18>
print(list(r),type(r))      # [5, 7, 9] <class 'map'>
r1 = map(add,x1,x3)
print(r1)       # <map object at 0x000002AD02C34D68>
print(list(r1))     # [2, 5]

自定义函数,两元素相加,传进去两个列表(长度按照最短的列表长度输出,请认真对比),map函数调用时,也可以传入两个参数在*iterables中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值