Вы можете просто перебирать свои числа и считать одинаковые или использовать itertools.groupby :
def count_em(l):
"""Returns a list of lenghts of consecutive equal numbers as list.
Example: [1,2,3,4,4,4,3,3] ==> [1,1,1,3,2]"""
if not isinstance(l,list):
return None
def count():
"""Counts equal elements, yields each count"""
# set the first elem as current
curr = [l[0]]
# for the rest of elements
for elem in l[1:]:
if elem == curr[-1]:
# append as long as the element is same as last one in curr
curr.append(elem)
else:
# yield the number
yield len(curr)
# reset curr to count the new ones
curr = [elem]
# yield last group
yield len(curr)
# get all yields and return them as list
return list(count())
def using_groupby(l):
"""Uses itertools.groupby and a list comp to get the lenghts."""
from itertools import groupby
grp = groupby(l) # this groups by the elems themselfs
# count the grouped items and return as list
return [ sum(1 for _ in items) for g,items in grp]
Тест:
A = [1,1,2,2]
B = [3,3,3,3,7,7,7]
C = [1,1,2,2,2,1,1,1,1,1,6,6]
for e in [A,B,C]:
print(count_em(e), using_groupby(e))
Вывод:
# count_em using_groupby Input
[2, 2] [2, 2] # [1,1,2,2]
[4, 3] [4, 3] # [3,3,3,3,7,7,7]
[2, 3, 5, 2] [2, 3, 5, 2] # [1,1,2,2,2,1,1,1,1,1,6,6]