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 184 views
1 answer 156 views
1 answer 160 views
160 views asked Jan 10, 2021 by avibootz
1 answer 159 views
...