Python 2.7 Grammar Geek - 列表理解中的Lambda

时间:2017-05-10 21:30:24

标签: python python-2.7 lambda list-comprehension grammar

您是否可以构建一个与以下Python 2.7 grammar rules匹配的最小有效源代码示例?是否可以不产生运行时错误?

(1) atom:           '[' [listmaker] ']'
(2) listmaker:      test  list_for
(3) list_for:       'for' exprlist 'in' testlist_safe
(4) testlist_safe:  old_test
(5) old_test:       old_lambdef
(6) old_lambdef:    'lambda' [varargslist] ':' old_test

到目前为止我能达到的最好结果是:

L = [ fn() for fn in (lambda: x for x in xrange(3)) ]

但我的解决方案的问题是围绕" lambda"的括号。你能不用括号建立一个例子吗?如果没有,那你怎么解释为什么你不能在lambda'即使它完全符合语法规则?

1 个答案:

答案 0 :(得分:5)

[x for x in lambda: 1]

这很简单。当然,这会在运行时产生TypeError,但语法不是为了排除会产生TypeErrors的构造。

没有办法在运行时没有异常,因为old_lambdef总是求值为一个不可迭代的函数对象。 old_lambdef的结构中没有任何地方可以插入一些东西来让Python调用函数; Python将尝试迭代函数对象本身,而不是调用它并迭代返回值。

testlist_safeold_test定义的完整形式为

testlist_safe: old_test [(',' old_test)+ [',']]
old_test: or_test | old_lambdef

testlist_safe并非总是单old_testold_test也不总是old_lambdef。允许testlist_safeold_testold_test允许old_lambdefgrid-container { display: grid; /* 1 */ grid-auto-rows: 50px; /* 2 */ grid-gap: 10px; /* 3 */ grid-template-columns: repeat(auto-fill, minmax(30%, 1fr)); /* 4 */ } [short] { grid-row: span 1; /* 5 */ background-color: green; } [tall] { grid-row: span 2; background-color: crimson; } [taller] { grid-row: span 3; background-color: blue; } [tallest] { grid-row: span 4; background-color: gray; }。一起做这些事情总是在运行时产生异常,但它们不会使语法复杂化只是为了阻止人们一起做这些事情。