How is map() implemented internally in Python?

Python里面的map函数是怎么实现的?


How is map() implemented internally in Python?

2 Answers
Bob Ippolito
Bob IppolitoCTO at Fig, Mission Bit board member, founder of Mochi Media. Python, JavaScr...
1.9k Views  •  Bob has  6 endorsements in  Python (programming language)
The implementation differs greatly depending on which Python you're talking about. In Python 2.x it's written in C but the code is roughly equivalent to the following:

             
             
  1. from itertools import izip
  2. def map(f, lst, *lsts):
  3. result = []
  4. for args in izip(lst, *lsts):
  5. result.append(f(*args))
  6. return result


In Python 3.x the implementation is also written in C, but it returns an iterable instead of a list, so the work doesn't happen eagerly. It is equivalent to the following (since zip is also lazy in Python 3, this is a pretty good approximation of what goes on under the hood):

             
             
  1. def map(f, lst, *lsts):
  2. for args in zip(lst, *lsts):
  3. yield f(*args)


To get the Python 3 behavior in Python 2, you can use  itertools.imap. To get Python 2 behavior in Python 3, you could use  list(map(…)).
Gurshabad Grover
Gurshabad Groverpseudorandom
642 Views
From the official Python documentation:

map(function, iterable, ...)
Apply  function to every item of  iterable and return a list of the results.


If a function definition makes anything clear, it would look something like this:

             
             
  1. def map(my_function, my_list):
  2. result = []
  3. for i in my_list:
  4. result.append(my_function(i))
  5. return result


But this is just simplifying since the map() function can process more than one iterable.

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 with None items. If function is None, 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.

I'd just like to add that using the map() function seems obsolete because list comprehensions do the same work in a more comprehensible (ha!) and faster manner.

my_list = [ my_function(x) for x in my_list]


2. Built-in Functions
Understanding the Map function. python
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值