Python Learning 1: Implement the Map function on your own

Source: Internet
Author: User

Assuming that Python does not provide a map () function, the My_map () function is programmed to implement the same functions as map (). The following code is implemented in Python 2.7.8.

Implementation code:

def my_map (Fun,num):
i = 0
x = list (len (num)) #创建一个list, length is the length of the input list
For n in Num: #对输入list中每个变量进行遍历
X[i] = Fun (n) #调取fun函数, and returns the result in X
i = i+1
Return x# returns x to
def my_sum (n):
Return 2*n

Test code:

print ' My_map: ', My_map (my_sum,[1,2,3,4,5,6,7])
print ' map: ', map (my_sum,[1,2,3,4,5,6,7])

Output Result:

My_map: [2, 4, 6, 8, 10, 12, 14]
Map: [2, 4, 6, 8, 10, 12, 14]

Easy to make mistakes:

No x is defined as list, that is, there is no x = list (len (num)), and the value of Fun (n) is assigned directly to X[i], which will quote typeerror: ' int ' object does not the support item Assignment, at this point, X is just an integer variable, not a list.

Python Learning 1: Implement the Map function on your own

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.