天天看點

Python程式設計:lambda替代品-operator子產品

代碼中不是很推薦使用 lambda表達式

取而代之的是 operator子產品,提供了很多簡單函數實作

求和示例(基于

Python 3.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 表達式了,不建議大家使用它