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