擅长:python、mysql、java
<p>您可以使用<code>sorted(set(element))</code>:</p>
<pre><code>>>> a = (0, 11, 100, 11, 33, 33, 55)
>>>
>>> sorted(set(a))[-1] # highest
100
>>> sorted(set(a))[-2] # second highest
55
>>>
</code></pre>
<p>作为功能:</p>
<pre><code>def nth_largest(li, n):
return sorted(set(li))[-n]
</code></pre>
<p>测试:</p>
<pre><code>>>> a = (0, 11, 100, 11, 33, 33, 55)
>>> def nth_largest(li, n):
... return sorted(set(li))[-n]
...
>>>
>>> nth_largest(a, 1)
100
>>> nth_largest(a, 2)
55
>>>
</code></pre>
<p>注意,这里只需要排序和删除一次重复,如果担心性能问题,可以缓存<code>sorted(set(li))</code>的结果。</p>