找到第二高的元素

2024-03-29 13:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 在给定的数组中,如何找到第二、第三、第四或第五个值?

  2. 如果我们在python中使用max()函数,那么复杂度的顺序是什么,也就是说,与这个函数相关的max()

是的。

def nth_largest(li,n):   
    li.remove(max(li))
    print max(ele)  //will give me the second largest
    #how to make a general algorithm to find the 2nd,3rd,4th highest value
    #n is the element to be found  below the highest value

Tags: theto函数顺序valuedefli数组
3条回答

如果性能是一个问题(例如:您打算经常调用它),那么您绝对应该始终对列表进行排序和消除重复,并且只保留第一个、第二个或第n个元素(即o(1))。

为此使用^{}模块-它比“标准”sort更快。

insort允许您插入一个元素,bisect将允许您查找是否应该插入(以避免重复)。


如果不是,我建议更简单的:

def nth_largest(li, n):.
    return sorted(set(li))[-(n+1)]

如果反向索引看起来很难看,可以执行以下操作:

def nth_largest(li, n):
    return sorted(set(li), reverse=True)[n]    

我会选择:

import heapq
res = heapq.nlargest(2, some_sequence)
print res[1] # to get 2nd largest

这比排序整个列表,然后获取第一个n多个元素更有效。有关详细信息,请参见heapq documentation

您可以使用sorted(set(element))

>>> a = (0, 11, 100, 11, 33, 33, 55)
>>>
>>> sorted(set(a))[-1] # highest
100
>>> sorted(set(a))[-2] # second highest
55
>>>

作为功能:

def nth_largest(li, n):
    return sorted(set(li))[-n]

测试:

>>> a = (0, 11, 100, 11, 33, 33, 55)
>>> def nth_largest(li, n):
...     return sorted(set(li))[-n]
...
>>>
>>> nth_largest(a, 1)
100
>>> nth_largest(a, 2)
55
>>>

注意,这里只需要排序和删除一次重复,如果担心性能问题,可以缓存sorted(set(li))的结果。

相关问题 更多 >