简体   繁体   中英

Add a number to a duplicated string in a list

Hi I have a list of values

ls = ["a", "a", "b", "b", "b", "b",  "c"]

And i wish to add an enumerating number to duplicates if ive used that term correctly.

Essentially I wnat to end up with this:

ls = ["a", "2a", "b", "2b", "3b", "4b",  "c"]

or this

ls = ["1a", "2a", "1b", "2b", "3b", "4b",  "1c"]

I just want each element of the list to be unique

This may not be the most effective way.

ls = ["a", "a", "b", "b", "b", "b",  "c"]

UniqueValues = set(ls)

for x in UniqueValues:
    number = 0
    for i in range(0,len(ls)):
        if ls[i] == x:
            number += 1
            if number >= 2:
                ls[i] += str(number)

but we get what you're looking for

print(ls)
['a', 'a2', 'b', 'b2', 'b3', 'b4', 'c']

So we need to check complete list each time so that if same value exists we can change the pointing value.

ls = ["a", "a", "b", "b", "b", "b",  "c",'a','a']

for index,value in enumerate(ls):

  if value in ls[index+1:]:

    for new in range(0,200000000):
      if not  f'{value}{new}' in ls:
        ls[index] = f'{value}{new}'
        break

print(ls)

Output:

['a0', 'a1', 'b0', 'b1', 'b2', 'b', 'c', 'a2', 'a']

You can use Counter and unique methods.

from numpy import unique
from collections import Counter

ls = ["a", "a", "b", "b", "b", "b",  "c"]

dup = dict(Counter(ls))
l_uniq = unique(ls)
print([key if i == 0 else key + str(i+1) for key in l_uniq for i in range(dup[key])])

Out:

['a', 'a2', 'b', 'b2', 'b3', 'b4', 'c']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM