Counter函数
时间: 2023-12-10 21:03:16 浏览: 34
Counter函数是Python中的一个内置函数,用于计算可迭代对象中元素出现的次数,并返回一个字典。它可以用于统计一段文本中每个单词出现的次数,或者统计一组数据中每个元素出现的次数等等。
下面是一个简单的例子,统计一个列表中元素出现的次数:
```python
from collections import Counter
lst = [1, 2, 3, 2, 1, 3, 4, 5, 6, 5, 5]
c = Counter(lst)
print(c)
```
输出结果为:
```
Counter({5: 3, 1: 2, 2: 2, 3: 2, 4: 1, 6: 1})
```
这个字典中的键对应着列表中的元素,值对应着该元素出现的次数。在上面的例子中,数字5出现了3次,数字1和2各出现了2次,数字3、4和6各出现了1次。
相关问题
python counter函数
Counter() 是 collections 库中的一个函数,可以用来统计一个 python 列表、字符串、元组等可迭代对象中每个元素出现的次数,并返回一个字典。你可以通过传入一个可迭代对象给 Counter() 函数来统计其中元素的出现次数。例如,可以使用 Counter() 来统计列表中的词频,字符串中的字符出现次数,或者元组中元素的出现次数。Counter() 函数返回的是一个字典,其中键是元素,值是该元素在可迭代对象中出现的次数。你还可以使用 most_common() 方法来查找出现频率最高的几个元素及其出现的次数。这个函数对于统计词频非常方便,可以避免手动使用 for 循环来统计词频。
import Counter函数
好的,您可以使用Python的`collections`模块中的`Counter`函数来进行单词计数,这样可以更加简洁和高效地实现该任务。以下是使用`Counter`函数的Python实现:
```python
from collections import Counter
# 读取文件内容
with open('in.txt', 'r') as f:
words = f.read().split()
# 统计单词出现次数
word_count = Counter(words)
# 按出现次数从大到小排序,次数相同的按单词从小到大排序
sorted_words = sorted(word_count.items(), key=lambda x: (-x[1], x[0]))
# 输出结果到文件
with open('out.txt', 'w') as f:
for word, count in sorted_words:
f.write(f"{word} {count}\n")
```
这个实现方式更加简洁,且使用了Python内置的高效计数函数`Counter`,可以更快地完成计数任务。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)