Python 中没有多行 Lambda:为什么不呢? [英] No Multiline Lambda in Python: Why not?

查看:35
本文介绍了Python 中没有多行 Lambda:为什么不呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说不能在 Python 中添加多行 lambda,因为它们会与 Python 中的其他语法结构在语法上发生冲突.我今天在公共汽车上思考这个问题,并意识到我想不出多行 lambda 会与之冲突的单个 Python 结构.鉴于我对这门语言非常了解,这让我感到惊讶.

I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.

现在,我确信 Guido 在语言中不包含多行 lambda 是有原因的,但出于好奇:在什么情况下包含多行 lambda 会不明确?我听说的是真的,还是有其他原因 Python 不允许多行 lambda 表达式?

Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?

推荐答案

请看以下内容:

map(multilambda x:
      y=x+1
      return y
   , [1,2,3])

这是一个返回 (y, [1,2,3]) 的 lambda(因此 map 只获取一个参数,导致错误)?还是返回y?或者是语法错误,因为新行的逗号放错了位置?Python 怎么知道你想要什么?

Is this a lambda returning (y, [1,2,3]) (thus map only gets one parameter, resulting in an error)? Or does it return y? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want?

在括号内,缩进对 python 无关紧要,所以你不能明确地使用多行.

Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines.

这只是一个简单的例子,可能还有更多的例子.

This is just a simple one, there's probably more examples.

这篇关于Python 中没有多行 Lambda:为什么不呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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