Python Example Method for Counting Number of Occurrences of List Elements
- 2021-10-16 02:14:59
- OfStack
1. Introduction
When using Python, the following scenarios usually appear:
array = [1, 2, 3, 3, 2, 1, 0, 2]
Gets the number of occurrences of elements in array
For example, in the above list: 0 appears once, 1 appears twice, 2 appears three times, and 3 appears twice.
In this paper, several methods of obtaining the number of elements in Python are described. Click to get the complete code.
2. Methodology
There are many ways to get the number of occurrences of elements. Here I propose the following five methods for reference. The following code, the parameters passed in are
array = [1, 2, 3, 3, 2, 1, 0, 2]
2.1 Counter method
This method can quickly get the number of elements appearing in list, and can refer to the official documents
from collections import Counter
def counter(arr):
return Counter(arr).most_common(2) # Returns the two most frequently occurring numbers
# Results: [(2, 3), (1, 2)]
2.2 count in list, getting the number of occurrences of each element
def single_list(arr, target):
return arr.count(target)
# target=2 Results: 3
2.3 count in list, getting the number of occurrences of all elements
Returns 1 dict
def all_list(arr):
result = {}
for i in set(arr):
result[i] = arr.count(i)
return result
# Results: {0: 1, 1: 2, 2: 3, 3: 2}
2.4 Numpy Fancy Index, which gets the number of occurrences of each element
def single_np(arr, target):
arr = np.array(arr)
mask = (arr == target)
arr_new = arr[mask]
return arr_new.size
# target=2 Results: 3
2.5 Numpy Fancy Index, which gets the number of occurrences of all elements
Returns 1 dict
def all_np(arr):
arr = np.array(arr)
key = np.unique(arr)
result = {}
for k in key:
mask = (arr == k)
arr_new = arr[mask]
v = arr_new.size
result[k] = v
return result
# Results: {0: 1, 1: 2, 2: 3, 3: 2}
3. Summary
These are several methods that I summarized for Python to get the number of elements.
It is worth mentioning that all elements of list I use are integers
array = [1, 2, 3, 3, 2, 1, 0, 2]
If list contains other types of elements, such as
array = [1, 2, 3, 3, 2, 1, 'a', 'bc', 0.1]
In this case, when you need to get the number of occurrences of a or 1, the call form of the function in 2.4 should be:
target='a' / target='1'