根据 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/