您当前的位置: 首页 >  彭世瑜 Python

Python编程:lambda替代品-operator模块

彭世瑜 发布时间:2019-05-10 22:50:33 ,浏览量:2

代码中不是很推荐使用 lambda表达式 取而代之的是 operator模块,提供了很多简单函数实现

求和示例(基于Python3.5.6)

# -*- coding: utf-8 -*-

import functools
import operator

lst = [1, 2, 3, 4, 5]

# 使用 lamabda
total = functools.reduce(lambda x, y: x + y, lst)
print(total) # 15

# 使用 operator.add
total = functools.reduce(operator.add, lst)
print(total) # 15

# 其实可以直接使用 sum
total = sum(lst)
print(total)  # 15

相关文章: 不要在Python中编写 lambda 表达式了,不建议大家使用它

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0558s