美文网首页
reduce, map,lambda

reduce, map,lambda

作者: Thinkando | 来源:发表于2018-11-25 14:53 被阅读21次

遇到一个很难看的代码

val = reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip([10, 20, 30], [0.1, 0.3, 0.7])), 0.0)
print(val)

28.0
  • 解读
print(list(zip([10, 20, 30], [0.1, 0.3, 0.7])))
[(10, 0.1), (20, 0.3), (30, 0.7)]

print(list(map(lambda t: t[0]*t[1], zip([10, 20, 30], [0.1, 0.3, 0.7]))))
[1.0, 6.0, 21.0]

print(reduce(lambda a, b: a+b, map(lambda t: t[0]*t[1], zip([10, 20, 30], [0.1, 0.3, 0.7])),0.0))
28.0
  • 代码一定要简单啊,不要追求什么酷炫啊
import numpy as np
a=sum(np.array([10,20,30])*np.array([0.1,0.3,0.7]))
print(a)

28.0
a = sum(x*w for x,w in zip([10, 20, 30], [0.1, 0.3, 0.7]))
print(a)

28.0

相关文章

网友评论

      本文标题:reduce, map,lambda

      本文链接:https://www.haomeiwen.com/subject/jiupqqtx.html