I have an array, for example [A,A,A,B,B,C,A,A,D,D,D,B]
I want to count the entries and convert it to this [3A,2B,1C,2A,3D,1B]
I have tried a load of if else type logic but I'm having issues. Is there a neat way to do this?
I have an array, for example [A,A,A,B,B,C,A,A,D,D,D,B]
I want to count the entries and convert it to this [3A,2B,1C,2A,3D,1B]
I have tried a load of if else type logic but I'm having issues. Is there a neat way to do this?
Seems like a good use of itertools.groupby:
from itertools import groupby
l = ['A','A','A','B','B','C','A','A','D','D','D','B']
[f'{len(list(g))}{k}' for k, g in groupby(l)]
# ['3A', '2B', '1C', '2A', '3D', '1B']
[list(g) for k,g in list(groupby(l))] gives empty lists and removing list() from groupby(l) works well why is that so?list(groupby(l)) uses up the iterator of the groups. This is explained in the docs with: "Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list". This allows it to work efficiently with large iterators.This is one way to solve this problem.
letters = ['A', 'A', 'A', 'B', 'B', 'C', 'A', 'A', 'D', 'D', 'D']
previous_letter = letters[0]
counter = 1
res = list()
for i in range(1, len(letters)):
current_letter = letters[i]
if current_letter == previous_letter:
counter += 1
else:
res.append(f"{counter}{current_letter}")
previous_letter = letters[i]
counter = 1
res.append(f"{counter}{previous_letter}")
print(res)
The trick is in checking a change of letters and keeping track of the count.
you could try using list.count() to get the number of times the first item appears then use list.pop(list.index()) in a for loop to remove all occurences of the first item, do this in a while loop until len(lst) returns 0
out = []
while len(lst) > 0:
s = lst[0]
c = 0
while len(lst) > 0:
if lst[0] == s:
c += 1
lst.pop(0)
out.append(f"{c}{s}")