Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append count numbers to duplicates in a list in Python?

Here is a list containing duplicates:

l1 = ['a', 'b', 'c', 'a', 'a', 'b']

Here is the desired result:

l1 = ['a', 'b', 'c', 'a_1', 'a_2', 'b_1']

How can the duplicates be renamed by appending a count number?


Here is an attempt to achieve this goal; however, is there a more Pythonic way?

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
like image 615
myeu2 Avatar asked Nov 27 '22 23:11

myeu2


2 Answers

In Python, generating a new list is usually much easier than changing an existing list. We have generators to do this efficiently. A dict can keep count of occurrences.

l = ['a', 'b', 'c', 'a', 'a', 'b']

def rename_duplicates( old ):
    seen = {}
    for x in old:
        if x in seen:
            seen[x] += 1
            yield "%s_%d" % (x, seen[x])
        else:
            seen[x] = 0
            yield x

print list(rename_duplicates(l))
like image 161
Jochen Ritzel Avatar answered Nov 30 '22 12:11

Jochen Ritzel


I would do something like this:

a1 = ['a', 'b', 'c', 'a', 'a', 'b']
a2 = []

d = {}

for i in a1:

    d.setdefault(i, -1)
    d[i] += 1

    if d[i] >= 1:
        a2.append('%s_%d' % (i, d[i]))
    else:
        a2.append(i)

print a2
like image 30
pzr Avatar answered Nov 30 '22 11:11

pzr