繁体   English   中英

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

[英]More pythonic way to find first two greatest value in a list in python

这些天我在python中设计了一些算法,但发现python中前两个最大的价值太丑陋且效率低下。

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

大多数 Pythonic 方法是使用nlargest

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

我发现这始终比heapq.nlargest更快(对于 1,000,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

(在 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
mylist = [100 , 2000 , 1 , 5]
mylist.sort()
biggest = mylist[-2:]

 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM