<p>您可以将<a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow noreferrer">^{<cd1>}</a>与<a href="http://docs.python.org/library/functions.html#map" rel="nofollow noreferrer">^{<cd2>}</a>结合使用,这对于小的<code>n</code>来说很快(注意<code>list.index</code>返回值为x的<strong>第一个</strong>项列表中的索引):</p>
<pre><code>>>> iterable = [100, 2, 400, 500, 400]
>>> map(iterable.index, heapq.nlargest(2, iterable))
[3, 2]
</code></pre>
<p>要查看关联的值。。。</p>
<pre><code>>>> map(lambda n: (n, iterable.index(n)), heapq.nlargest(2, iterable))
[(500, 3), (400, 2)]
</code></pre>
<p>有关更大的<code>n</code>请参阅@silenghost的帖子。</p>
<hr/>
<p>编辑:对一些解决方案进行基准测试:</p>
<pre><code>#!/usr/bin/env python
import heapq
from timeit import Timer
seq = [100, 2, 400, 500, 400]
def a(seq):
"""returns [(3, 500), (2, 400)]"""
return heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])
def b(seq):
"""returns [3, 2]"""
return map(seq.index, heapq.nlargest(2, seq))
def c(seq):
"""returns [(500, 3), (400, 2)]"""
map(lambda n: (n, seq.index(n)), heapq.nlargest(2, seq))
if __name__ == '__main__':
_a = Timer("a(seq)", "from __main__ import a, seq")
_b = Timer("b(seq)", "from __main__ import b, seq")
_c = Timer("c(seq)", "from __main__ import c, seq")
loops = 1000000
print _a.timeit(number=loops)
print _b.timeit(number=loops)
print _c.timeit(number=loops)
# Core i5, 2.4GHz, Python 2.6, Darwin
# 8.92712688446
# 5.64332985878
# 6.50824809074
</code></pre>