I have a Python list and I want to know what's the quickest way to count the number of occurrences of the item, '1'
in this list. In my actual case, the item can occur tens of thousands of times which is why I want a fast way.
['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
Does the collections
module help? I'm using Python 2.7
By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.
If our python list is:-
To find occurrence of every items in the python list use following:-
To find most/highest occurrence of items in the python list:-
For Highest one:-
For the item just use k[0][0]
For nth highest item and its no of occurrence in the list use follow:-
**for n=2 **
Combination of lambda and map function can also do the job:
You can use
pandas
, by transforming thelist
to apd.Series
then simply use.value_counts()
You can convert list in string with elements seperated by space and split it based on number/char to be searched..
Will be clean and fast for large list..
It's probably optimized heavily at the C level.
Edit: I randomly generated a large list.
Edit edit: This could be done with collections.Counter
Using the same list in my last timing example
My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.
Here is some profiling