How to add item counter in a list with Python

1 Answer

0 votes
from collections import defaultdict 
  
lst = ["python", "php", "java", "c++", "php", "php", "c++"] 
 
dd = defaultdict(int) 

result = [] 
for item in lst: 
    dd[item] += 1
    result.append((item, dd[item])) 
  
print(result) 



'''
run:

[('python', 1), ('php', 1), ('java', 1), ('c++', 1), ('php', 2), ('php', 3), ('c++', 2)]

'''

 



answered Dec 27, 2019 by avibootz

Related questions

1 answer 269 views
1 answer 249 views
1 answer 238 views
238 views asked Jan 10, 2021 by avibootz
1 answer 249 views
...