我需要定義一個函數,將列表縮減為單個整數。該函數接受兩個參數。一個“組合器”:告訴我們應該如何減少列表以及列表本身。以下是要求的結果:
Combines elements in the list lst using a combiner function.
As you can see, the combiner function takes two arguments.
It reduces the list to a single integer, depending on the combiner function.
>>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
10
>>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
24
>>> reduce(lambda x, y: x * y, [4])
4
關于如何正確定義第一個論點,我一直在爭論不休。如何對列表中應使用的函數進行編程?或者我甚至需要在這里做一個If/Else-Statement?
我的直覺到現在為止:
def reduce(combiner, lst):
plus_func = lambda x, y: x + y
mult_func = lambda x, y: x * y
if combiner == plus_func:
n = 0
for i in lst:
n += i
return n
elif combiner == x * y:
n = 1
for i in lst:
n * i
return n
如何告訴函數應用哪個lambda?
您需要使用傳遞給
reduce
的函數(lambda):