is there a better way of replacing duplicates in a list (python)

Posted by myeu2 on Stack Overflow See other posts from Stack Overflow or by myeu2
Published on 2010-05-14T20:30:06Z Indexed on 2010/05/14 20:34 UTC
Read the original article Hit count: 196

Filed under:
|
|

Given a list:

  • l1: ['a', 'b', 'c', 'a', 'a', 'b']
  • output: ['a', 'b', 'c', 'a'_1, 'a'_2, 'b'_1 ]

I created the following code to get the output. Its messyyy..

for index in range(len(l1)):
    counter = 1
    list_of_duplicates_for_item = [dup_index for dup_index, item in enumerate(l1) if item == l1[index] and l1.count(l1[index]) > 1]
    for dup_index in list_of_duplicates_for_item[1:]: 
        l1[dup_index] = l1[dup_index] + '_' + str(counter)
        counter = counter + 1

Is there a more pythonic way of doing this? I couldnt find anything on the web.

© Stack Overflow or respective owner

Related posts about python

Related posts about duplicate