私信  •  关注

Enzo

Enzo 最近创建的主题
Enzo 最近回复了
4 年前
回复了 Enzo 创建的主题 » Python问题使用map,lambda,过滤和减少一个函数

以下是仅使用缩减的方法:

import functools

def max_book_product(orders):
    items = functools.reduce(lambda a, b: a + b[1:], orders, [])
    books = functools.reduce(lambda books, item: {**books, item[0]: books.get(item[0], 0) + item[1] * item[2]}, items, {})
    return functools.reduce(lambda a, b: a if a[1] > b[1] else b, books.items())

你可以看看 functools.reduce documentation :它作为第一个参数接收函数,作为第二个参数接收iterable to reduce,作为第三个参数接收reduce的初始值。因为我认为这是家庭作业,所以解释留给读者作为练习。