I am trying to make a function that counts elements in a list and I am using Python for that. The program should accept a list like [a, a, a, b, b, c, c, c, c]
and returns a value [3, 2, 4]
but I am having trouble. What should I do?
Asked
Active
Viewed 298 times
1
-
possible duplicate https://stackoverflow.com/questions/12282232/how-do-i-count-unique-values-inside-an-array-in-python – Frayal Aug 23 '18 at 08:10
-
1`print( [lst.count(i) for i in set(lst)] ) ` ? – Rakesh Aug 23 '18 at 08:10
-
1How will you know that 3 belongs to a, 2 to b and 4 to c? – colidyre Aug 23 '18 at 08:12
-
3use `collections.Counter`. – Daniel Aug 23 '18 at 08:12
-
1Possible duplicate of [How to count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item) – Julien Aug 23 '18 at 08:13
-
1What should the function do given `[a, a, a, b, b, a]`? Return `[4, 2]` or `[3, 2, 1]`? – L3viathan Aug 23 '18 at 08:19
-
Yes I could use a built in function but I am trying not to – kgemp Aug 23 '18 at 08:37
2 Answers
3
If when given ['a', 'a', 'a', 'b', 'b', 'a']
you want [3, 2, 1]
:
import itertools
result = [len(list(iterable)) for _, iterable in itertools.groupby(my_list)]

L3viathan
- 26,748
- 2
- 58
- 81
-
1just an addition: `[(k, sum(1 for _ in v)) for k, v in itertools.groupby(my_list)]` is an example how to get also the mapping of the counted elements. – colidyre Aug 23 '18 at 10:53
1
Use a dict and make a counter out of it.
a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = {}
for i in inp:
if i in dic:
dic[i]+=1
else:
dic[i] = 1
print(dic) #Dict with input values and count of them
print(dic.values()) #Count of values in the dict
Remember that this change the order of input list. To keep the order intact, use OrderedDict method from Collections library.
from collections import OrderedDict
a,b,c = "a","b","c"
inp = [a,a,a,b,b,c,c,c,c]
dic = OrderedDict()
for i in inp:
if i in dic:
dic[i]+=1
else:
dic[i] = 1
print(dic)
print(dic.values())

Raviteja Ainampudi
- 282
- 1
- 11