python - 无法决定是否应该使用高阶函数
问题描述
简单的方法
def add(listt, addend):
sums = list()
for l in listt: sums.append(l + addend)
return sums
print(
add(
[34,19], 6)
)
WITH HIGHER-ORDER FUNCTION(来自教学函数式编程的一页)
def hof_add(increment):
# Create a function that loops and adds the increment
def add_increment(numbers):
new_numbers = []
for n in numbers:
new_numbers.append(n + increment)
return new_numbers
# We return the function as we do any other value
return add_increment
add5 = hof_add(5)
print(add5([23, 88])) # [28, 93]
add10 = hof_add(10)
print(add10([23, 88])) # [33, 98]
哪种方法是更好的实践?什么时候需要高阶函数?
解决方案
推荐阅读
- macos - 如何从 Mac 上的 Xbox One 控制器读取蓝牙输入流
- typescript - 如何从函数泛型获取分配返回类型
- python - 使用 BeautifulSoup 在 python 中抓取 xPaths
- python - 你能用 tweepy 只询问 10 个趋势吗?
- rest - 实现类似 Stripe 的基本身份验证
- c++ - 在超类中定义但在子类中实现的方法:访问子类属性?
- r - 特征选择后的贝叶斯优化 (R)
- vba - 在 MS Word 中的“另存为”事件后更新所有字段?
- javascript - 如何在同一个空间设置多个sideToggles?
- html - 如何强制 Instagram 应用内网络浏览器刷新页面?