这是一道面试题:
代码如下所示:
from functools import reduce
l = [1, 2, 3, 4, 5, 6]
"""
1.取出偶数下标:filter
filter(lambda x:x%2==0, range(len(list))) ==>[0,2,4]
2.取出对应下标值:map
map(lambda x:list[x],filter(lambda x:x%2==0, range(len(list)))) ==>[1,3,5]
3.对应值加3:lambda
map(lambda x:x+3,map(lambda x:list[x],filter(lambda x:x%2==0, range(len(list))))) ==>[4,6,8]
4.将数组求和reduce 也可以用sum()函数
reduce(lambda x,y: x+y,map(lambda x:x+3,map(lambda x:list[x],filter(lambda x:x%2==0, range(len(list))))))
"""
l2 = reduce(lambda x, y : x + y, map(lambda i: l[i]+3, list(filter(lambda y:y%2 == 0, range(len(l))))))
l3 = sum(list(map(lambda i: l[i]+3, list(filter(lambda y:y%2 == 0, range(len(l)))))))
print(l2)
print(l3)
输出结果为:
18 18 |