Skip to content Skip to sidebar Skip to footer

Get Top 5 Largest From List Of Tuples - Python

I have a list of tuples like this (generated from a select statement with sqlite3): itemsAndQtyBought = [('Item no.1', 3), ('Item no.2', 0), ('Item no.3', 3), ('Item no.4', 2), ('I

Solution 1:

Just use sorted and slice the first 5 items:

In [170]: sorted(itemsAndQtyBought, key=lambda t: t[1], reverse=True)[:5]
Out[170]:
[('Item no.6', 9),
 ('Item no.7', 7),
 ('Item no.1', 3),
 ('Item no.3', 3),
 ('Item no.4', 2)]

Solution 2:

You can use heapq.nlargest():

from heapq import nlargest
from operator import itemgetter

nlargest(5, my_list, key=itemgetter(1))

heapq.nlargest(n, iterable[, key])

Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in the iterable: key=str.lower Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

Output:

>>>my_list = [('Item no.1', 3), ('Item no.2', 0),...           ('Item no.3', 3), ('Item no.4', 2),...           ('Item no.5', 1), ('Item no.6', 9),...           ('Item no.7', 7)]>>>>>>nlargest(5, my_list, key=itemgetter(1))
[('Item no.6', 9), ('Item no.7', 7), ('Item no.1', 3), ('Item no.3', 3), ('Item no.4', 2)]

Solution 3:

sorted(itemsAndQtyBought, key=lambda item: item[1], reverse=True)[:5]

Output:

[('Item no.6', 9), ('Item no.7', 7), ('Item no.1', 3), ('Item no.3', 3), ('Item no.4', 2)]

Only drawback: It sorts the whole list

Solution 4:

Hope it will help you

from operator import itemgetter

defnewItem(oldItem):
        newItemQtyBought = sorted(oldItem,key=itemgetter(1))
        return newItemQtyBought[-5:]

defmain():
        itemsAndQtyBought = [('Item no.1', 3), ('Item no.2', 0), ('Item no.3', 3), ('Item no.4', 2), ('Item no.5', 1), ('Item no.6', 9), ('Item no.7', 7)]
        print(newItem(itemsAndQtyBought))

if __name__=="__main__":
        main()

Post a Comment for "Get Top 5 Largest From List Of Tuples - Python"