One: Define a list array to find the number of occurrences of each element in the array
If implemented in Java, is a more complex, need to traverse the array list.
But Python is simple: look at the code
[Python]View Plain Copy
- A = [1,4,2,3,2,3,4,2]
- From collections Import Counter
- Print Counter (a)
Printing results:
Counter ({2:3, 3:2, 4:2, 1:1})
The results show that element 2 appears 3 times, Element 3 appears 2 times, element 4 occurs 2 times, and element 1 appears 1 times.
Second: Find the most frequently occurring elements in an array
Look directly at the code:
[Python]View Plain Copy
- A = [1,4,2,3,2,3,4,2]
- From collections Import Counter
- Print Counter (a). Most_commo (1)
Operation Result:
[(2, 3)]
Continue to modify the code:
[Python]View Plain Copy
- A = [1,4,2,3,2,3,4,2]
- From collections Import Counter
- Print Counter (a)
- Print Counter (a). Most_common (2)
Operation Result:
[(2, 3), (3, 2)]
Three: summary
(1) The collection class is introduced from the Collections Collection module counter
(2) Counter (a) can print the number of occurrences of each element in Group A
(3) Counter (a). Most_common (2) can print the most frequently occurring elements in the array. The meaning of parameter 2 is that it outputs several elements that have the most occurrences.
Transferred from: http://blog.csdn.net/u013628152/article/details/43198605
Counter () count in Python