thestp123
thestp123

Reputation: 159

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), ('Item no.5', 1), ('Item no.6', 9), ('Item no.7', 7)]

And the list carries on. It's a list of tuples and its got a product name and the quantity bought of that item.

I need to create anoter list of tuples of the top 5 items from that list of tuples with 5 of the items with the highest quantity bought.

For example with the list above it would turn out like this:

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

Is there any way to do this?

Thanks for any answers.

Upvotes: 4

Views: 8207

Answers (4)

Aman Jaiswal
Aman Jaiswal

Reputation: 1093

Hope it will help you

from operator import itemgetter

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

def main():
        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()

Upvotes: 0

ettanany
ettanany

Reputation: 19816

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

Upvotes: 7

salparadise
salparadise

Reputation: 5805

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

Upvotes: 13

helloV
helloV

Reputation: 52423

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

Upvotes: 2

Related Questions