擅长:python、mysql、java
<pre><code>>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4
</code></pre>
<p><a href="http://docs.python.org/tutorial/controlflow.html#lambda-forms" rel="noreferrer">lambda</a>是编写“匿名”函数(没有名称的函数)的一种特殊方式。因为lambda是一个表达式,所以可以为它指定任何名称。</p>
<p>写上述内容的“长”方法是:</p>
<pre><code>def takeClosest(num,collection):
return min(collection,key=lambda x:abs(x-num))
</code></pre>