How to add count for each unique val in list
You can use a Counter
or a defaultdict(int)
to keep track of how many times a character has been seen as you encounter them.
>>> from collections import Counter
>>>
>>> temp = ['A', 'B', 'A', 'B', 'A', 'B']
>>> seen = Counter()
>>>
>>> result = []
>>> for c in temp:
...: seen.update(c)
...: result.append('{}_{}'.format(c, seen[c]))
...:
>>> result
>>> ['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3']
Note that seen.update(c)
might have unexpected results if you expect strings with more than one character in temp
. Demo:
>>> seen = Counter()
>>> seen.update('ABC')
>>> seen
>>> Counter({'A': 1, 'B': 1, 'C': 1})
Depending on how you want to count and what kind of data you expect, you might want to use the line
seen[c] += 1
instead of
seen.update(c)
Alternatively, without any imports:
>>> seen = {}
>>> result = []
>>>
>>> for c in temp:
...: seen[c] = seen.get(c, 0) + 1
...: result.append('{}_{}'.format(c, seen[c]))
...:
>>> result
>>> ['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3']
You can use collections.defaultdict
with a for
loop:
from collections import defaultdict
L = ['A', 'B', 'A', 'B', 'A', 'B']
dd = defaultdict(int)
res = []
for item in L:
dd[item] += 1
res.append(f'{item}_{dd[item]}')
print(res)
['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3']