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

前端 未结 7 2010
情书的邮戳
情书的邮戳 2020-12-13 18:41

Given a list like this:

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

I would like to rename the duplicate

7条回答
  •  庸人自扰
    2020-12-13 19:24

    Less fancy stuff.

    from collections import defaultdict
    mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
    finalList = []
    dictCount = defaultdict(int)
    anotherDict = defaultdict(int)
    for t in mylist:
       anotherDict[t] += 1
    for m in mylist:
       dictCount[m] += 1
       if anotherDict[m] > 1:
           finalList.append(str(m)+str(dictCount[m]))
       else:
           finalList.append(m)
    print finalList
    

提交回复
热议问题