假设python没有提供map()函数,请自行编写一个my_map()函数实现与map()相同的

如题所述

#python的map, filter, reduce等函数都是为了简化,方便循环list的函数。
#所以如果不用的话,就相当于把for循环展开
L = [1,2,3,4,5]
def my_map(L):
    result = []
    for e in L:
        result.append(e*2+1)
    return result
print map(lambda x:x*2+1, L)#输出[3, 5, 7, 9, 11]
print my_map(L)#输出[3, 5, 7, 9, 11]
#不用函数
print [x*2+1 for x in L]#输出[3, 5, 7, 9, 11]
#不用函数 è®¡ç®—大于等于3的
print [x*2+1 for x in L if x >= 3]#输出[7, 9, 11]
#使用map filter è®¡ç®—大于等于3的,
print map(lambda x:x*2+1, filter(lambda x:x>=3,L))#输出[7, 9, 11]
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-25
def my_map(f,l):
  
    return [f(x) for x in l]