从元组列表中获取最大的5个Python

2024-09-30 20:33:33 发布

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

我有一个这样的元组列表(从带有sqlite3的select语句生成):

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

名单还在继续。这是一个元组的列表,它有一个产品名称和购买该商品的数量。在

我需要创建另一个元组列表,其中前5个项目的元组列表中有5个项目的购买量最高。在

例如,上面的列表会是这样的:

^{pr2}$

有办法吗?在

谢谢你的回答。在


Tags: 项目列表数量语句itemselectsqlite3商品
3条回答

只需使用排序和切片前5项:

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)]
sorted(itemsAndQtyBought, key=lambda item: item[1], reverse=True)[:5]

输出:

^{pr2}$

唯一的缺点是:它会对整个列表进行排序

您可以使用^{}

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]

输出:

^{pr2}$

相关问题 更多 >