python map lambda reduce

 
 

问题:将一个list的每个数变为其的平方


普通的处理

list_x = [1,2,3,4,5,6,7,8]
def square(x):
    return x*x
for x in range(0,len(list_x)):
    list_x[x] = square(list_x[x])
    print(list_x[x])
print(list_x)
 
map处理:
list_x = [1,2,3,4,5,6,7,8]
def square(x):
    return x*x
r = map(square,list_x)
print(type(r))

print(list(r))

输出如下:

<class 'map'>[1, 4, 9, 16, 25, 36, 49, 64]


map和lambda处理

list_x = [1,2,3,4,5,6,7,8]
r = map(lambda x:x*x,list_x)
print(list(r))

当lambda里有多个参数时,对应的个数去取最小的那个参数个数

list_x = [1,2,3,4,5,6,7,8]
list_y = [1,2,3,4,5,6,7]
r = map(lambda x,y:x+y,list_x,list_y)
print(list(r))




reduce

# from functools import reduce
#
# list_x = ['1','2','3','4','5','6']
# r = reduce(lambda x,y:x+y,list_x,'aa') #第三个参数可为无
# print(type(r))
# print(r)

# map/reduce 编程模型  映射  归约  并行计算
# 函数式编程
#步伐移动 (横坐标,纵坐标)
from functools import reduce

list_go=[(1,2),(2,-3),(-2,3),(9,8)]
r = reduce(lambda x,y:(x[0]+y[0],x[1]+y[1]),list_go)
print(type(r))
print(r)
<class 'tuple'>
(10, 10)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值