python中reduce函数使用详解

在python3.6的版本中reduce函数的使用也发生了改变,使用前需要先导入模块:

基本使用方法如下:

`

import functools 

def test(x, y):

    return x+y



my_list = [1, 2, 3, 4]

new_value = functools.reduce(test, my_list) 

print(new_value)


<p style="margin-top: 1em; margin-bottom: 1em; padding: 0px; border: 0px; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-stretch: inherit; font-size: 15px; line-height: 2; font-family: normal, "Avenir Next", Avenir, "Helvetica Neue", Helvetica, "Hiragino Sans GB", 微软雅黑, sans-serif; vertical-align: baseline; overflow-wrap: break-word; word-break: break-all; box-sizing: border-box; color: rgb(30, 30, 30); white-space: normal; background-color: rgb(255, 255, 255);">其执行的逻辑是:循环my_list数组,第一次取出1和2分别赋值给x和y,test函数执行完毕后将得到的结果赋值给x即第一个参数,再拿出3给y继续执行,一直到遍历完所有的元素
</p><p style="margin-top: 1em; margin-bottom: 1em; padding: 0px; border: 0px; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-stretch: inherit; font-size: 15px; line-height: 2; font-family: normal, "Avenir Next", Avenir, "Helvetica Neue", Helvetica, "Hiragino Sans GB", 微软雅黑, sans-serif; vertical-align: baseline; overflow-wrap: break-word; word-break: break-all; box-sizing: border-box; color: rgb(30, 30, 30); white-space: normal; background-color: rgb(255, 255, 255);">上面是复杂的写法,reduce也有像map函数一样的lambda写法:
</p><pre class="line-numbers language-python code-toolbar" style="padding: 1em; border: 1px dashed rgb(204, 204, 204); font-variant-numeric: inherit; font-variant-east-asian: inherit; font-stretch: inherit; font-size: 12px; line-height: 1.5; font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace; vertical-align: baseline; overflow-wrap: normal; word-break: normal; box-sizing: border-box; text-shadow: white 0px 1px; tab-size: 4; background-color: rgb(245, 242, 240); hyphens: none; overflow: auto; position: relative;"><span style="color: rgb(0, 0, 0);">import functools<br></br>my_list = [1, 2, 3, 4]<br></br>new_value = functools.reduce(lambda x, y: x+y , my_list, 2)<br></br>print(new_value)</span><br></br>

这种写法更简洁

`

王如棋博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论