0
点赞
收藏
分享

微信扫一扫

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


代码中不是很推荐使用 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



举报

相关推荐

0 条评论