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

查看:111
本文介绍了为什么要使用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.

在我所看到的大多数示例中,这似乎更多是一种风格或结构上的选择.并且kinda打破了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天全站免登陆