Python中数组所有元素的频率计数
在本教程中,我们将编写一个程序来查找数组中所有元素的频率。我们可以通过不同的方法找到它,让我们探索其中的两种。
使用字典
初始化数组。
初始化一个空**字典**。
遍历列表。
如果元素不在字典中,则将其值设置为**1**。
否则将值递增**1**。
通过遍历字典打印元素和频率。
示例
让我们看看代码。
# intializing the list
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# initializing dict to store frequency of each element
elements_count = {}
# iterating over the elements for frequency
for element in arr:
# checking whether it is in the dict or not
if element in elements_count:
# incerementing the count by 1
elements_count[element] += 1
else:
# setting the count to 1
elements_count[element] = 1
# printing the elements frequencies
for key, value in elements_count.items():
print(f"{key}: {value}")输出
如果您运行上述程序,您将获得以下结果。
1: 3 2: 4 3: 5
让我们看看使用collections模块的Counter类的第二种方法。
使用Counter类
导入**collections**模块。
初始化数组。
将列表传递给**Counter**类。并将结果存储在一个变量中。
通过遍历结果打印元素和频率。
示例
请看下面的代码。
# importing the collections module
import collections
# intializing the arr
arr = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]
# getting the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
print(f"{key}: {value}")输出
如果您运行上述代码,您将获得与前一个相同的输出。
1: 3 2: 4 3: 5
结论
如果您对本教程有任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP