3

I was doing a small program that count the number of times that a character appears in a list and I have a question, ¿Is possible to do it by consecutive numbers?. I have this code now:

def function(list):
    final_list = []
    for element in set(list):
        final_list.append([element, list.count(element)])
    return final_list
Amartin
  • 337
  • 2
  • 17

1 Answers1

7

For a simpler solution, you could use itertools.groupby:

from itertools import groupby
l = [1, 1, 1, 2, 2, 3, 4, 4, 1, 1, 1]

[[k,len(list(v))] for k,v in groupby(l)]
# [[1, 3], [2, 2], [3, 1], [4, 2], [1, 3]]
yatu
  • 86,083
  • 12
  • 84
  • 139