python将accum简化为参数
根据SO中的线程,python将accum简化为参数,python,reduce,Python,Reduce,根据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) 这里,我
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中传递初始累加器值的方式是什么。根据,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)
接受累加器作为第三个参数谢谢。我希望我错过了。这似乎是一个答案。我无法理解,因为许多示例不使用第三个参数。