pst
pst

Reputation: 92

Append in list depending of if the value already exists in it

I have an empty list. I want to append strings in it but if they already exist to change them a bit. Something like this:

Names : John , David, John, Luis, Sean, John, David

the list after appending : John, David, John_2, Luis, Sean, John_3, David_2

I was thinking something like this:

            names_list = []
            names = [ 'John' , 'David', 'John', 'Luis, 'Sean', 'John', 'David']
            itter = 1
            for _ in names:
                if any(names[_] in s for s in name_list):
                    button_list.append(names[_] + f'_{itter+1}')
                    itter+=1
                else:
                    button_list.append(names[_])

This however gives us : John, David, John_2, Luis, Sean, John_3, David_4 ( where last David needs to be David_2). I cannot find a way to change the itter depending on the number of occurrences of a specific name. Thanks for your help in advance.

Upvotes: 1

Views: 520

Answers (3)

Marko
Marko

Reputation: 382

You could also use the count method on a sublist from the beginning to the current value, like this:

names = [ 'John' , 'David', 'John', 'Luis', 'Sean', 'John', 'David']
names_list = []
for i in range(len(names)):
    name = names[i]
    count = names[:i].count(name)  # count the names in the sublist
    if count:
        names_list.append(f"{name}_{count+1}")
    else:
        names_list.append(name)

print(names_list)
#  ['John', 'David', 'John_2', 'Luis', 'Sean', 'John_3', 'David_2']

Upvotes: 0

Paul M.
Paul M.

Reputation: 10819

You will need a separate itter for each distinct name, to keep track of the separate counts. One way to do it would be with collections.Counter:

def rename(names):
    from collections import Counter

    counter = Counter()

    for name in names:
        counter.update([name])
        count = counter[name]
        suffix = "" if count == 1 else f"_{count}"
        yield f"{name}{suffix}"
        

names = ["John", "David", "John", "Luis", "Sean", "John", "David"]
print(list(rename(names)))

Output:

['John', 'David', 'John_2', 'Luis', 'Sean', 'John_3', 'David_2']
>>> 

Upvotes: 2

Mayank Porwal
Mayank Porwal

Reputation: 34086

You can have a generator like this:

In [3215]: 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] = 1
      ...:             yield x
      ...: 

In [3216]: list(rename_duplicates(names))
Out[3216]: ['John', 'David', 'John_2', 'Luis', 'Sean', 'John_3', 'David_2']

Upvotes: 2

Related Questions