myeu2
myeu2

Reputation: 199

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

Upvotes: 4

Views: 3584

Answers (5)

Hossein Kalbasi
Hossein Kalbasi

Reputation: 1861

I wrote this approach for renaming duplicates in a list with any separator and a numeric or alphabetical postfix (e.g. _1, _2 or _a, _b, _c etc.). Might not be the best you could write efficient-wise, but I like this as a clean readable code which is also scalable easily.

def rename_duplicates(label_list, seperator="_", mode="numeric"):

    """
    options for 'mode': numeric, alphabet

    """
    import string

    if not isinstance(label_list, list) or not isinstance(seperator, str):
        raise TypeError("lable_list and separator must of type list and str, respectively")

    for item in label_list:

        l_count = label_list.count(item)

        if l_count > 1:

            if mode == "alphabet":
                postfix_str = string.ascii_lowercase

                if len(postfix_str) < l_count:
                    # do something
                    pass

            elif mode == "numeric":
                postfix_str = "".join([str(i+1) for i in range(l_count)])

            else:
                raise ValueError("the 'mode' could be either 'numeric' or 'alphabet'")

            postfix_iter = iter(postfix_str)

            for i in range(l_count):
                item_index = label_list.index(item)
                label_list[item_index] += seperator + next(postfix_iter)

    return label_list

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

use the function: rename_duplicates(label_list)

result: ['a_1', 'b_1', 'c', 'a_2', 'a_3', 'b_2']

Upvotes: 0

Don O&#39;Donnell
Don O&#39;Donnell

Reputation: 4728

Based on your comment to @mathmike, if your ultimate goal is to create a dictionary from a list with duplicate keys, I would use a defaultdict from the `collections Lib.

>>> from collections import defaultdict
>>> multidict = defaultdict(list)
>>> multidict['a'].append(1)
>>> multidict['b'].append(2)
>>> multidict['a'].append(11)
>>> multidict
defaultdict(<type 'list'>, {'a': [1, 11], 'b': [2]})

Upvotes: 1

Jochen Ritzel
Jochen Ritzel

Reputation: 107608

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))

Upvotes: 20

mathmike
mathmike

Reputation: 1014

I think the output you're asking for is messy itself, and so there is no clean way of creating it.

How do you intend to use this new list? Would a dictionary of counts like the following work instead?

{'a':3, 'b':2, 'c':1}

If so, I would recommend:

from collections import defaultdict
d = defaultdict(int) # values default to 0
for key in l1:
    d[key] += 1

Upvotes: 0

pzr
pzr

Reputation: 1256

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

Upvotes: 5

Related Questions