Python's method of counting the number of occurrences of duplicates in a list

  • 2020-04-02 13:59:14
  • OfStack

This article illustrates Python's method of counting the number of repetitions in a list, which is a useful feature for beginners to learn from. Specific methods are as follows:

For a list like [1,2,2,2,2,3,3,3,4,4,4,4], we now need to count the number of duplicates in the list and count the number of duplicates.

Method 1:


mylist = [1,2,2,2,2,3,3,3,4,4,4,4]
myset = set(mylist)  #myset That's another list, and that's what's in there mylist There is no repetition   item 
for item in myset:
  print("the %d has found %d" %(item,mylist.count(item)))

Method 2:


List=[1,2,2,2,2,3,3,3,4,4,4,4]
a = {}
for i in List:
  if List.count(i)>1:
    a[i] = List.count(i)
print (a)

Take advantage of the dictionary feature.

Method 3:


>>> from collections import Counter
>>> Counter([1,2,2,2,2,3,3,3,4,4,4,4])
Counter({1: 5, 2: 3, 3: 2})

Here is another list-only method:


l=[1,4,2,4,2,2,5,2,6,3,3,6,3,6,6,3,3,3,7,8,9,8,7,0,7,1,2,4,7,8,9]

count_times = []
for i in l :
  count_times.append(l.count(i))

m = max(count_times)
n = l.index(m)

print (l[n])

The principle is to record the number of occurrences of each number in the list in its corresponding position, and then use Max to find the position with the most occurrences.
Using this code alone has the disadvantage that if there are multiple results, the end result is only the one that appears on the far left, but the solution is simple

Interested readers can take a hands-on look at the code described in this article, and improve on the shortcomings to make it more functional.


Related articles: