1

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?

colidyre
  • 4,170
  • 12
  • 37
  • 53
kgemp
  • 69
  • 4

2 Answers2

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
  • 1
    just 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())