Python中的项目频率计数 [英] Item frequency count in Python

查看:33
本文介绍了Python中的项目频率计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个单词列表,我想找出每个单词在该列表中出现的次数.

Assume I have a list of words, and I want to find the number of times each word appears in that list.

一个明显的方法是:

words = "apple banana apple strawberry banana lemon"
uniques = set(words.split())
freqs = [(item, words.split().count(item)) for item in uniques]
print(freqs)

但是我觉得这段代码不太好,因为程序会遍历单词列表两次,一次是构建集合,第二次是统计出现次数.

But I find this code not very good, because the program runs through the word list twice, once to build the set, and a second time to count the number of appearances.

当然,我可以编写一个函数来遍历列表并进行计数,但这不会那么 Pythonic.那么,有没有更高效和 Pythonic 的方式?

Of course, I could write a function to run through the list and do the counting, but that wouldn't be so Pythonic. So, is there a more efficient and Pythonic way?

推荐答案

<collections 模块中的 code>Counter 类 专门用于解决此类问题:

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

这篇关于Python中的项目频率计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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