[Python] python中reduce用法 →→→→→进入此内容的聊天室

来自 , 2021-03-19, 写在 Python, 查看 129 次.
URL http://www.code666.cn/view/d7488039
  1. >>> def myfunction(a,b):
  2. ...     return a*b
  3. ...
  4. >>> mylist = [1,2,3,4,5]
  5. >>> print reduce(myfunction, mylist)
  6. 120
  7.  
  8. #上面的代码相当于:
  9. >>>print ((((1*2)*3)*4)*5)
  10. 120
  11.  
  12. #也可以直接使用操作符模块来替代函数
  13. >>> import operator
  14. >>> mylist = [1,2,3,4,5]
  15. >>> print reduce(operator.mul, mylist)
  16. 120
  17. >>> print reduce(operator.add, mylist)
  18. 15
  19. #//python/833

回复 "python中reduce用法"

这儿你可以回复上面这条便签

captcha