【问题标题】:Python: apply a list of lambda functions to a list without loopsPython:将 lambda 函数列表应用于没有循环的列表
【发布时间】:2020-02-03 22:05:54
【问题描述】:

我有一个 lambda 函数列表和一个我想要应用这些函数的分数列表。

我想在应用这些 lambda 函数后返回一个包含最大分数的新列表。

例如:

calculate_best_scores([lambda x : x + 1, lambda x : x * 2,\
lambda x : x - 1], [3, 4, 5]) will return [6, 8, 10] --- the max individual max score after applying the lambda function to.

谁能给我建议,告诉我如何只使用 lambda 函数和映射、过滤和减少而不显式使用循环?

谢谢!

【问题讨论】:

  • 你不必说“lambda 函数”。函数就是一个函数,无论是由 lambda 表达式还是 def 语句定义。
  • “给我建议”很难回答,除非简单地给你一个完整的解决方案——我们尽量不在这里做。在完成有关该主题的教程后,您走了多远?您需要将第一个列表中的每个函数 map 第二个列表中的每个值,然后为每个值选择最大值——我猜你已经知道了。

标签: python dictionary lambda filter


【解决方案1】:

你可以试试这个:

>>> functions = [lambda x : x + 1, lambda x : x * 2, lambda x : x - 1]
>>> data = [3, 4, 5]
>>> result = [max([f(x) for f in functions]) for x in data]
>>> result
[6, 8, 10]

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2023-02-02
    相关资源
    最近更新 更多