我正在使用 lambda 函数来检查最大值,传递 3 个参数
from functools import reduce
# function to check bigger item
f = lambda a,b,c: a if (a > b) else (b if (b > c) else c)
# reduce function
reduce(f, [47, 11, 42, 102, 13])
但是我得到这样的错误
TypeError Traceback (most recent call last)
5 6 # reduce function 7 reduce(f, [47, 11, 42, 102, 13, 21]) TypeError: <lambda>() missing 1 required positional argument: 'c'
请您参考如下方法:
如果您正在寻找列表中最大的元素,一次比较三个元素的工作方式与一次比较两个元素的方式相同。这两种方式花费相同的时间。甚至你创建了一个像 reduce 这样的函数,但一次需要 3 个元素,你的想法有缺陷,因为如果列表由 4 或 6 或 8 或...元素组成,它仍然无法按预期工作。
from functools import reduce
# function to check bigger item
g = lambda a,b: a if (a > b) else b
f(1,3,4)
# reduce function
reduce(g, [47, 11, 42, 102, 13])
