python中的map

本文详细介绍了Python中map()函数的使用方法,包括单个及多个可迭代参数的应用,并展示了如何利用该函数进行数据转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MapReduce的设计灵感来自于函数式编程,这里不打算提MapReduce,就拿python中的map()函数来学习一下。

文档中的介绍在这里:

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

一点一点看:

1、对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回。

来个例子:

>>> def add100(x):
...     return x+100
... 
>>> hh = [11,22,33]
>>> map(add100,hh)
[111, 122, 133]
就像文档中说的:对hh中的元素做了add100,返回了结果的list。


2、如果给出了额外的可迭代参数,则对每个可迭代参数中的元素‘并行’的应用‘function’。(翻译的不好,这里的关键是‘并行’)

>>> def abc(a, b, c):
...     return a*10000 + b*100 + c
... 
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(abc,list1,list2,list3)
[114477, 225588, 336699]
看到并行的效果了吧!在每个list中,取出了下标相同的元素,执行了abc()。


3、如果'function'给出的是‘None’,自动假定一个‘identity’函数(这个‘identity’不知道怎么解释,看例子吧

>>> list1 = [11,22,33]
>>> map(None,list1)
[11, 22, 33]
>>> list1 = [11,22,33]
>>> list2 = [44,55,66]
>>> list3 = [77,88,99]
>>> map(None,list1,list2,list3)
[(11, 44, 77), (22, 55, 88), (33, 66, 99)本文来自于:http://my.oschina.net/zyzzy/blog/115096我是快乐的搬运工、、、、、、O(∩_∩)O哈哈~总结一下
第一个参数接收一个函数名,第二个参数接收一个可迭代对象


  
ls =  [ 1 , 2 , 3 ]
rs =  map ( str , ls)
 
#打印结果 ['1', '2', '3']
lt =  [ 1 , 2 , 3 , 4 , 5 , 6 ]
def  add(num):
     return  num +  1
 
rs =  map (add, lt)
print  rs #[2,3,4,5,6,7]

  

 

ls =  [ 1 , 2 , 3 ]
rs =  map ( str , ls)
 
#打印结果 ['1', '2', '3']
lt =  [ 1 , 2 , 3 , 4 , 5 , 6 ]
def  add(num):
     return  num +  1
 
rs =  map (add, lt)
print  rs #[2,3,4,5,6,7]

  

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值