To accomplish this task there many possible ways , I'll try to list here most of them.
- 1- A simple approach :
def countX(l, x):
count = 0
for i in l:
if (i == x): # check wether x is equal to i
count = count + 1 we increment the counter by one
return count
- 2 - using count method :
def countX(l, x):
return l.count(x)
- 3 - using Counter method :
from collections import Counter #first we import the method
def countX(l,x) :
d = Counter(l) # d is a dictionary containing each number as a key and the
# number of occurrences as a value
return '{} has occurred {} times'.format(x, d[x])
- 4 - using countOf method :
# import Operator module
import operator
def countX(l,x) :
count = operator.countOf(l, x) # gives the number of occurrences of x in l
return count
- 5 - using a combination of lambda and map
def countX(l,x) :
a = sum(map(lambda v: v == x, l))
- 6 - using the pandas module :
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
def countX(l,x) :
count = pd.Series(l).value_counts().to_dict()
return count[str(x)]
Sources :
Buy Website Traffic
0 Comments