Python - map, reduce 練習

  1. map(func,seq), 將序列seq中的元素取出來,依次放到Func函數,將結果以列表形式返回,支持多參數

e.g

a = [1,2,3,4]
def add(x):
    return x+3

listmap = map(add,a)
for i in listmap:
    print i,

返回:4 5 6 7


      2. reduce(func,iterable),例如reduce(lambda x,y:x+y,[1,2,3,4,5])實際上就是求和:((1+2)+3)+4)+5)

練習:

list1 = [1,2,3,4]
list2 = [5,6,7,8]
求list1[0]list2[0]+list1[1]list2[1]...
有兩種方法:
1.
list1 = [1,2,3,4]
list2 = [5,6,7,8]
listTemp = map(lambda x:x*10,list1)
listResult = map(lambda x,y:x+y,listTemp,list2)
result = sum(listResult)
print result
2.
更簡潔的方法,是用zip:
list3 = [x*10 + y for x,y in zip(list1,list2)]
print sum(list3)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章