计算Python中数组中所有元素的频率

在本教程中,我们将编写一个程序来查找数组中所有元素的频率。我们可以通过不同的方式找到它,让我们探究其中两个。

使用字典

  • 初始化数组。

  • 初始化一个空字典

  • 遍历列表。

    • 如果该元素不在dict中,则将值设置为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类

  • 导入集合模块。

  • 初始化数组。

  • 将列表传递给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

结论

如果您对本教程有任何疑问,请在评论部分中提及。