0

Can someone can help me how to enumerate the elements of a list to label the counting the occurrences of the elements, i.e.,

list_in = ['a','b','c']
list_out =  ['a-1','b-1','c-1']
list_in = ['a','b','a']
list_out =  ['a-1','b-1','a-2']
list_in = ['a','a','a']
list_out =  ['a-1','a-2','a-3']
funie200
  • 3,688
  • 5
  • 21
  • 34
Romero-Reina Juan
  • 111
  • 1
  • 1
  • 4

4 Answers4

1

You could count the occurances of each item in list_in:

list_in1 = ['a', 'b', 'c']
list_in2 = ['a', 'b', 'a']
list_in3 = ['a', 'a', 'a']


def reformat(list_in):
    counts = {item: list(range(list_in.count(item))) for item in set(list_in)}
    out = [f"{item}-{counts[item].pop(0)+1}" for item in list_in]
    print(out)


for list_in in (list_in1, list_in2, list_in3):
    reformat(list_in)

Out:

['a-1', 'b-1', 'c-1']
['a-1', 'b-1', 'a-2']
['a-1', 'a-2', 'a-3']
1

Here is one way of doing it:

list_in = ['a','b','c']

lst_new = [list_in[x]+'-'+str(list_in[0:x+1].count(list_in[x])) for x in range(len(list_in))]

print(lst_new)
JacksonPro
  • 3,135
  • 2
  • 6
  • 29
0

I wrote one but its not in the same sequence though as in the original list.

>>> from collections import Counter

>>> def enum(listy):
>>>     counter = Counter(listy)
>>>     final = []
>>>     for val in range(len(counter)):
>>>         alp, times = counter.popitem()
>>>         temp = []
>>>         for p in range(1, times+1):
>>>             temp.append(alp+'-'+str(p))
>>>         final.extend(temp)
        
>>>     return final

>>> list_in = ['a','b','a']

>>> print(enum(list_in))
['b-1', 'a-1', 'a-2']
Amit Amola
  • 2,301
  • 2
  • 22
  • 37
0

You could count the number of letters preceding each one in the list and format the result in a list comprehension:

list_in  = ['a','b','a']

list_out = [f"{c}-{list_in[:i].count(c)+1}" for i,c in enumerate(list_in)]

# ['a-1', 'b-1', 'a-2']
Alain T.
  • 40,517
  • 4
  • 31
  • 51