标签: python
如果我有一个清单,例如[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 0], and I want to find the the two largest numbers (which are 9 and 9`),我怎么能实现这一目标?而且,如果可能的话,我怎样才能获得他们的指数?
[1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 0], and I want to find the the two largest numbers (which are
and
答案 0 :(得分:2)
您可以使用heapq模块,特别是nlargest方法:
heapq
nlargest
>>> import heapq >>> mylist = [1,2,3,4,5,6,7,8,9,9,9,0] >>> heapq.nlargest(2, mylist) [9, 9]
要查找索引,您需要枚举列表:
>>> mydata = heapq.nlargest(2, enumerate(mylist), key=lambda x:x[1]) >>> indexes, values = zip(*mydata) >>> print indexes, values (8, 9) (9, 9)