从元组列表中获取前5名最大的组件-Python [英] Get top 5 largest from list of tuples - Python

查看:129
本文介绍了从元组列表中获取前5名最大的组件-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我需要从该元组列表中创建前5个项目的元组注释列表,其中有5个项目的购买量最高.

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

有什么办法吗?

感谢您的回答.

推荐答案

只需使用已排序并切片的前5个项目:

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

这篇关于从元组列表中获取前5名最大的组件-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆