List elements’ counter
Instead of listcomp as in another solution you can use the function itemgetter
:
from collections import Counter
from operator import itemgetter
lst = ["a", "b", "c", "c", "a", "c"]
c = Counter(lst)
itemgetter(*lst)(c)
# (2, 1, 3, 3, 2, 3)
UPDATE: As @ALollz mentioned in the comments this solution seems to be the fastet one. If OP needs a list instead of a tuple the result must be converted wih list
.
Use np.unique
to create a dictionary of value counts and map the values. This will be fast, though not as fast as the Counter methods:
import numpy as np
list(map(dict(zip(*np.unique(MyList, return_counts=True))).get, MyList))
#[2, 1, 3, 3, 2, 3]
Some timings for a moderate sized list:
MyList = np.random.randint(1, 2000, 5000).tolist()
%timeit [MyList.count(i) for i in MyList]
#413 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(map(dict(zip(*np.unique(MyList, return_counts=True))).get, MyList))
#1.89 ms ± 1.73 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit pd.DataFrame(MyList).groupby(MyList).transform(len)[0].tolist()
#2.18 s ± 12.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
c=Counter(MyList)
%timeit lout=[c[i] for i in MyList]
#679 µs ± 2.33 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
c = Counter(MyList)
%timeit list(itemgetter(*MyList)(c))
#503 µs ± 162 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Larger list:
MyList = np.random.randint(1, 2000, 50000).tolist()
%timeit [MyList.count(i) for i in MyList]
#41.2 s ± 5.27 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(map(dict(zip(*np.unique(MyList, return_counts=True))).get, MyList))
#18 ms ± 56.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit pd.DataFrame(MyList).groupby(MyList).transform(len)[0].tolist()
#2.44 s ± 12.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
c=Counter(MyList)
%timeit lout=[c[i] for i in MyList]
#6.89 ms ± 22.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
c = Counter(MyList)
%timeit list(itemgetter(*MyList)(c))
#5.27 ms ± 10.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
You can use the list.count
method, which will count the amount of times each string takes place in MyList
. You can generate a new list with the counts by using a list comprehension:
MyList = ["a", "b", "c", "c", "a", "c"]
[MyList.count(i) for i in MyList]
# [2, 1, 3, 3, 2, 3]