擅长:python、mysql、java
<p>我可以在这里给出几个不同的答案,从你的具体问题到更普遍的问题。所以从最具体到最一般:</p>
<p><strong>Q.</strong>你能在lambda中放入多个语句吗?</p>
<p><strong>A.</strong>不需要。但实际上不需要使用lambda。您可以将语句放在<code>def</code>中。即:</p>
<pre><code>def second_lowest(l):
l.sort()
return l[1]
map(second_lowest, lst)
</code></pre>
<p><strong>Q.</strong>你能通过对列表进行排序从lambda中得到第二低的项吗?</p>
<p><strong>A.</strong>是。正如<a href="https://stackoverflow.com/questions/862412/is-it-possible-to-have-multiple-statements-in-a-python-lambda-expression/862430#862430">alex's answer</a>所指出的,<code>sorted()</code>是sort的一个版本,它创建了一个新列表,而不是就地排序,并且可以被链接。请注意,这可能是您应该使用的-这是不好的做法,您的地图有副作用的原始名单。</p>
<p><strong>Q.</strong>如何从一系列列表中的每个列表中获取第二个最低的项。</p>
<p><strong>A.</strong><code>sorted(l)[1]</code>实际上不是最好的方法。当存在O(N)解时,它具有O(N log(N))复杂性。这可以在heapq模块中找到。</p>
<pre><code>>>> import heapq
>>> l = [5,2,6,8,3,5]
>>> heapq.nsmallest(l, 2)
[2, 3]
</code></pre>
<p>所以只要使用:</p>
<pre><code>map(lambda x: heapq.nsmallest(x,2)[1], list_of_lists)
</code></pre>
<p>通常还认为使用列表理解更清楚,这样可以完全避免lambda:</p>
<pre><code>[heapq.nsmallest(x,2)[1] for x in list_of_lists]
</code></pre>