TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Python does support if-else in lambdas...

7 点作者 globalrev超过 16 年前
Just learned some tricks in #python in IRC-freenode:<p>I have heard a lot of complaints about Pythons lambdas being crippled but Python does allow if-else in lambdas, I didn't know before. Not in the ordinary Python way but:<p>f = lambda n_: (lambda ns: ns.__setitem__('f', lambda n: n if n in [0, 1] else \ fib(n-1) + fib(n - 2)) or ns['f'](n_))({})<p>map(lambda n: n<i></i>3 if n % 2 == 1 else n<i></i>2, range(10))<p>&#62;&#62;&#62; reduce(lambda x,y: x+y if y % 2 == 1 else x-y, [1,2,3,4,5]) 3<p>&#62;&#62;&#62; fib = lambda n: n if n in [0, 1] else fib(n-1) + fib(n - 2) &#62;&#62;&#62; fib(12) 144<p>also: [n<i></i>3 if n%2 else n<i></i>2 for n in range(10)]<p>For soem reason * * disappears if next to each other.

3 条评论

kaens超过 16 年前
That's the normal python idiom for the ternary operator in other languages if I'm not mistaken. Its lambdas are still crippled, for the same reasons people called them crippled before, which is fine for python, IMO.<p>If I recall correctly, the if...else for ternary was added mainly because people were doing stuff with and...or to achieve the same effect.
评论 #358864 未加载
thomasmallen超过 16 年前
* * disappears because those are for italizicing text here. Obviously they should really only be hidden if they're surrounding something.
tzury超过 16 年前
That's the way I write these if..else statements fib = lambda n: n in [0, 1] and n or fib(n-1) + fib(n - 2)