Python counts the number of occurrences of elements in an array

If you only need to count the number of occurrences of a certain element, you can directly use the count function to achieve it.
The code is as follows:

my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
print(my_list.count(-1))

If you want to return the number of occurrences of each element, you can use the following two methods:

method one:

from collections import Counter
my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
counter = Counter(my_list)
print(counter)
# 也可转为字典类型
print(dict(counter))

The output is as follows:

Counter({
    
    4: 4, 2: 2, -1: 2, 1: 1, 5: 1, 6: 1})
{
    
    1: 1, 2: 2, -1: 2, 4: 4, 5: 1, 6: 1}

Method Two:

my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
result = {
    
    }
for value in set(my_list):
  result[value] = my_list.count(value)
print(result)

Output result:

{
    
    1: 1, 2: 2, 4: 4, 5: 1, 6: 1, -1: 2}

The order of elements output by the two methods is different.

Guess you like

Origin blog.csdn.net/JingpengSun/article/details/130943398