How to add count for each unique val in list

  • A+
Category:Languages

Assume I have a list.

temp = ['A', 'B', 'A', 'B', 'A', 'B'] 

I am looking for a way to join the count of the string inside.

Intended Output:

['A_1', 'B_1', 'A_2', 'B_2', 'A_3', 'B_3'] 

I was able to solve it by using a list comprehension but I am looking for a way where I don't have to specify the list [1, 1, 2, 2, 3, 3]. Is it possible?

[j + "_" + str(i) for i, j in zip([1, 1, 2, 2, 3, 3], temp)] 

 


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'] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: