更多pythonic方法在python中查找列表中的前两个最大值

时间:2012-06-11 07:37:06

标签: python

这些天我在python中设计了一些算法,但在python中找到前两个最大的值是太丑陋和低效。

如何以高效或pythonic的方式实现它?

4 个答案:

答案 0 :(得分:16)

大多数Pythonic方式是使用nlargest

import heapq
values = heapq.nlargest(2, my_list)

答案 1 :(得分:5)

我发现这一点比heapq.nlargest更快(约为1,000,000项目列表的2倍):

def two_largest(sequence):
    first = second = 0
    for item in sequence:
        if item > second:
            if item > first:
                first, second = item, first
            else:
                second = item
    return first, second

(根据MatthieuW的建议修改的功能)

以下是我的测试结果(timeit正在进行中,所以我使用time.time()):

>>> from random import shuffle
>>> from time import time
>>> seq = range(1000000)
>>> shuffle(seq)
>>> def time_it(func, *args, **kwargs):
...     t0 = time()
...     func(*args, **kwargs)
...     return time() - t0
...

>>> #here I define the above function, two_largest().
>>> from heapq import nlargest
>>> time_it(nlargest, 2, seq)
0.258958101273
>>> time_it(two_largest, seq)
0.145977973938

答案 2 :(得分:1)

mylist = [100 , 2000 , 1 , 5]
mylist.sort()
biggest = mylist[-2:]

答案 3 :(得分:0)

a=int(input('Enter the first number:'))
b=int(input('Enter the second Number:'))
c=int(input('Ente the Third Number:'))
if a>b and a>c:
    print('the value of A is',a,'highest velue')
elif b>a and b>c:
    print('the value of B is',b,'highest velue')
elif c>a and c>b:
    print('the value of C is',c,'highest velue')
else:
   print('the value is equls')