如何从Python列表中获取具有相应出现次数的唯一值? [英] How to get unique values with respective occurrence count from a list in Python?

查看:95
本文介绍了如何从Python列表中获取具有相应出现次数的唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含重复项目的列表,我想要一个具有其频率的唯一项目列表.

I have a list which has repeating items and I want a list of the unique items with their frequency.

例如,我有['a', 'a', 'b', 'b', 'b'],我想要[('a', 2), ('b', 3)].

寻找一种简单的方法来执行此操作而无需循环两次.

Looking for a simple way to do this without looping twice.

推荐答案

如果将您的商品归为一组(即,类似的商品组合在一起),则最有效的使用方法是itertools.groupby:

If your items are grouped (i.e. similar items come together in a bunch), the most efficient method to use is itertools.groupby:

>>> [(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]
[('a', 2), ('b', 3)]

这篇关于如何从Python列表中获取具有相应出现次数的唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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