Python: Rename duplicates in list with progressive numbers without sorting list -


given list this:

mylist = ["name", "state", "name", "city", "name", "zip", "zip"] 

i rename duplicates appending number following result:

mylist = ["name1", "state", "name2", "city", "name3", "zip1", "zip2"] 

i not want change order of original list. solutions suggested related stack overflow question sorts list, not want do.

this how it.

mylist = ["name", "state", "name", "city", "name", "zip", "zip"]  collections import counter # counter counts number of occurrences of each item counts = counter(mylist) # have: {'name':3, 'state':1, 'city':1, 'zip':2} s,num in counts.items():     if num > 1: # ignore strings appear once         suffix in range(1, num + 1): # suffix starts @ 1 , increases 1 each time             mylist[mylist.index(s)] = s + str(suffix) # replace each appearance of s 

edit: here in one-liner, order not preserved.

[s + str(suffix) if num>1 else s s,num in counter(mylist).items() suffix in range(1, num+1)] # produces: ['zip1', 'zip2', 'city', 'state', 'name1', 'name2', 'name3'] 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -