[英]Fold Higher Order Function Using Lambda Expressions
我想编写一个 function ,它采用 function 并使用列表返回结果。
#Sum_two
sum_two = lambda x, y: x + y
#Longer
def longer(s, t):
# Take two strings
# Return the longer
# Return the first if equal in length
if len(s) >= len(t):
return s
else:
return t
def fold(f,x):
return [item for item in x if f(item)]
这是它应该做的:
>>> fold(sum_two, [1, 2, 3, 4, 5])
15
>>> fold(longer, ['aa', 'bb', 'cccc', 'd'])
cccc
它只会崩溃。 我不知道如何解决它,需要帮助。 这不是另一个问题的重复,因为它正在修复我的代码,而不是如何解决问题。 这也不是功课,只是更好地理解高阶函数的一种方法。
可悲的是,这不会那么简单。 列表推导返回列表并且不应该用于副作用,因此它们在这里并不是真正的正确工具。 您可能只需要编写一个循环:
def fold(f,x):
start, *rest = x
for item in rest:
start = f(start, item)
return start
fold(sum_two, [1, 2, 3, 4, 5])
# 15
fold(longer, ['aa', 'bb', 'cccc', 'd'])
# 'cccc'
如果您不想自己做,还有functools.reduce()
。
您需要返回单个值。 正如@MarkMeyer 指出的那样,您可以遍历列表,但也可以递归实现fold
:
def fold(f,x):
if len(x) < 2:
return x[0]
elif len(x) == 2:
return f(x[0], x[1])
else:
return f(x[0], fold(f, x[1:]))
fold(sum_two, [1, 2, 3, 4, 5])
# 15
fold(longer, ['aa', 'bb', 'cccc', 'd'])
# 'cccc'
也许你可以使用reduce:
from functools import reduce
sum_two = lambda x,y:x+y
longer = lambda x,y:x if len(x) >= len(y) else y
print(reduce(sum_two,[1,2,3,4,5]))
# 15
print(reduce(longer,['aa', 'bb', 'cccc', 'd']))
# cccc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.