这些天我在python中设计了一些算法,但是在python中找到前两个最大的值是太丑陋和低效.
如何以高效或pythonic的方式实现它?
int*_*jay 16
大多数Pythonic方式是使用nlargest:
import heapq
values = heapq.nlargest(2, my_list)
Run Code Online (Sandbox Code Playgroud)
我发现这一点比一般更快(约1,000件物品清单的2倍)heapq.nlargest:
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
Run Code Online (Sandbox Code Playgroud)
(根据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
Run Code Online (Sandbox Code Playgroud)