I need to indexing a list of string because I don't want duplicates to avoid the overwritting when I rename files.
Let's say that I have a liste like this one :
list = ['name', 'city', 'city', 'name1', 'town', 'city2', 'town', 'name2']
And I would like to get a list like this one :
list = ['name3', 'city1', 'city3', 'name1', 'town1', 'city2', 'town2', 'name2']
To do that I was inspired by this post :
Python: Rename duplicates in list with progressive numbers without sorting list
And I wrote this code that doesn't ! Can anyone find what it misses or tell me if it is completly wrong !
def unique(mylist):
newlist = []
for i, v in enumerate(mylist):
totalcount = mylist.count(v)
print('Step 1, totalcount : '+ str(totalcount))
count = mylist[:i].count(v)
print('Step 2, count : '+ str(count))
if totalcount > 1 :
print('Logic test :' + str(bool((v + str(count + 1)) in mylist)))
while (v + str(count + 1)) in mylist :
count += 1
list[i] = v + str(count+1)
else :
list[i] = v
newlist.append(list[i])
print('Step 3 : '+str(newlist))
return newlist
The result of my code is :
['name', 'city1', 'city', 'name1', 'town1', 'city2', 'town', 'name2']
Because I can find the code, I am thinking to apply a function that removes only the last digits of a string like the following function and then indexing with one of the codes present in the link. However, I would find more elegant to do it directly. What do you think ?
def delete_digit_end(string):
name_parts=re.findall(r'[^\d_]+|[^\D]+|[^\W_]+|[\W_]+', string) # this part creates a list by splitting the digits,
# letters and '-_'
lenght=len(name_parts)-1 #we want to analize the last element of the list, if it contains digits or '_-'
# We do a loop while to test if the parts have digits or '-_', if true we execute the loop until it is false
while name_parts[lenght].isdigit() :
# if it is true it will remove them
name_parts[lenght]=''# it will remove them
lenght -= 1 # if the condition was true, we continue with one inferior part
new_string = ''.join(map(str,name_parts))# now that we have cleaned if it was necessary we concatenate them
return new_string