deuces
deuces

Reputation: 41

python List Duplicates Identify and assign a value

I have a list like L=[A,B,B,C,C,C] I need the resultant list to be L=[A,B-1,B-2,C-1,C-2,C-3] i.e all the duplicates need to have a running number while keeping the order same

Upvotes: 1

Views: 38

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 114035

You could use itertools.groupby to find "runs" of elements and build a new list from there:

import itertools

L = [A,B,B,C,C,C]
answer = []
for _k, group in itertools.groupby(L):
    group = list(group)
    if len(group) == 1:
        answer.extend(group)
        continue
    answer.extend(("{}-{}".format(e,i) for i,e in enumerate(group, 1)))

Upvotes: 1

Related Questions