Py学习  »  Python

Python问题使用map,lambda,过滤和减少一个函数

bart • 3 年前 • 1448 次点击  

我想编辑这个函数,这样就没有 for 循环:仅使用映射、lambda和reduce。

它将以下列表作为输入:

orders = [[1, ("5464", 4, 9.99), ("8274", 18, 12.99), ("9744", 9, 44.95)], 
          [2, ("5464", 9, 9.99), ("9744", 9, 44.95)],
          [3, ("5464", 9, 9.99), ("88112", 11, 24.99)],
          [4, ("8732", 7, 11.99), ("7733", 11, 18.99), ("88112", 5, 39.95)]]

并返回所需的输出:

['9744', 809.1]

然而,它仍然存在 对于 循环,我怎样才能摆脱它们?

def max_book_product(orders):
    dictionary = {}
    for order in orders:
        for book in order[1]:
            if book[0] in dictionary:
                dictionary[book[0]] += book[1] * book[2]
            else:
                dictionary[book[0]] = book[1] * book[2]
    sorted_items = sorted(dictionary.items(), key=lambda tup: tup[1])
    return list(sorted_items.pop())
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131362
 
1448 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Enzo
Reply   •   1 楼
Enzo    3 年前

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

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的初始值。因为我认为这是家庭作业,所以解释留给读者作为练习。