为什么要使用 lambda 函数? [英] Why use lambda functions?

查看:28
本文介绍了为什么要使用 lambda 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以找到很多东西向我展示什么是 lambda 函数,以及语法如何工作以及什么不工作.但除了酷因素"(我可以在调用另一个函数的中间调用一个函数,太棒了!)我还没有看到一些非常引人注目的东西来说明我为什么真的需要/想要使用它们.

I can find lots of stuff showing me what a lambda function is, and how the syntax works and what not. But other than the "coolness factor" (I can make a function in middle a call to another function, neat!) I haven't seen something that's overwelmingly compelling to say why I really need/want to use them.

在我见过的大多数示例中,这似乎更像是一种风格或结构选择.并且有点打破了python规则中的做某事的唯一正确方法".它如何使我的程序更正确、更可靠、更快或更易于理解?(我见过的大多数编码标准都倾向于告诉您避免在一行中使用过于复杂的语句.如果这样更易于阅读,请将其分解.)

It seems to be more of a stylistic or structual choice in most examples I've seen. And kinda breaks the "Only one correct way to do something" in python rule. How does it make my programs, more correct, more reliable, faster, or easier to understand? (Most coding standards I've seen tend to tell you to avoid overly complex statements on a single line. If it makes it easier to read break it up.)

推荐答案

这是一个很好的例子:

def key(x):
    return x[1]

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)

对比

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=lambda x: x[1])

换个角度:Lambda 表达式也被称为匿名函数",在某些编程范式中非常有用,特别是函数式编程,这是 lambda 演算提供的灵感.

From another angle: Lambda expressions are also known as "anonymous functions", and are very useful in certain programming paradigms, particularly functional programming, which lambda calculus provided the inspiration for.

http://en.wikipedia.org/wiki/Lambda_calculus

这篇关于为什么要使用 lambda 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆