python reduce accum 作为参数

标签 python reduce

根据 this线程在SO中,reduce相当于fold。然而,在 Haskell 中,accum 参数也被传递给 fold。 python中reduce传递累加器的方式是什么。

my_func(accum, list_elem):
     if list_elem > 5:
       return accum and True # or just accum
     return accum and False # or just False

reduce(my_func, my_list)

在这里,我想将 True 作为累加器传递。 python中传递初始累加器值的方式是什么。

最佳答案

根据 documentation , reduce 接受可选的第三个参数作为累积初始值设定项。

你可以这样写:

def my_func(acc, elem):
    return acc and elem > 5

reduce(my_func, my_list, True)

或者,使用 lambda:

reduce(lambda a,e: a and e > 5, my_list, True)

或者,对于这个特定的例子,如果你想检查 5 是否严格小于所有 my_list 中的元素,你可以使用

greater_than_five = (5).__lt__
all(greater_than_five, my_list)

关于python reduce accum 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166493/

相关文章:

python - 从 Python 中的嵌套字典中提取键

python - 如何在 python 中展平列表的嵌套列表?

hadoop - reducer 未在hadoop中执行

python - 遍历多个文件的所有行的最 pythonic 方法是什么?

python - 如何通过(索引,列)检查 pandas DataFrame 条目是否存在

python - 在 Python 中将一个元组添加到一个元组

python - 使用 PyParsing 解析系统日志

hadoop - 当我运行带有多个对象的创建请求时,Hadoop Hive保持卡住

scala - 减少一组空集是否有效?

python - 如何从 python 为 Electron 应用程序创建数据库