Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Apr 22 19:35:36 EDT 2010


On Thu, 22 Apr 2010 10:49:29 -0700, John Nagle wrote:

>    Is "nlargest" smart enough to decide when it's cheaper to track the
> N largest entries on a linear pass through the list than to sort?

Doesn't appear to do so. From Python 3.1:

def nlargest(n, iterable):
    """Find the n largest elements in a dataset.

    Equivalent to:  sorted(iterable, reverse=True)[:n]
    """
    it = iter(iterable)
    result = list(islice(it, n))
    if not result:
        return result
    heapify(result)
    _heappushpop = heappushpop
    for elem in it:
        _heappushpop(result, elem)
    result.sort(reverse=True)
    return result


although if there is a C implementation, Python will use that instead of 
the above, and that may be different.

Interestingly, nsmallest does use two different algorithms, depending on 
how many items you ask for. See the source code.



-- 
Steven



More information about the Python-list mailing list