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']
Which approach: .count
or collections.Counter
is likely more optimized?
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
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..
>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
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:-
l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
To find occurrence of every items in the python list use following:-
\>>from collections import Counter
\>>c=Counter(l)
\>>print c
Counter({'1': 6, '2': 4, '7': 3, '10': 2})
To find most/highest occurrence of items in the python list:-
\>>k=c.most_common()
\>>k
[('1', 6), ('2', 4), ('7', 3), ('10', 2)]
For Highest one:-
\>>k[0][1]
6
For the item just use k[0][0]
\>>k[0][0]
'1'
For nth highest item and its no of occurrence in the list use follow:-
**for n=2 **
\>>print k[n-1][0] # For item
2
\>>print k[n-1][1] # For value
4
Source: Stackoverflow.com