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

前端 未结 7 2003
情书的邮戳
情书的邮戳 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:45

    Any method where count is called on each element is going to result in O(n^2) since count is O(n). You can do something like this:

    # not modifying original list
    from collections import Counter
    
    mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
    counts = {k:v for k,v in Counter(mylist).items() if v > 1}
    newlist = mylist[:]
    
    for i in reversed(range(len(mylist))):
        item = mylist[i]
        if item in counts and counts[item]:
            newlist[i] += str(counts[item])
            counts[item]-=1
    print(newlist)
    
    # ['name1', 'state', 'name2', 'city', 'name3', 'zip1', 'zip2']
    

    # modifying original list
    from collections import Counter
    
    mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
    counts = {k:v for k,v in Counter(mylist).items() if v > 1}      
    
    for i in reversed(range(len(mylist))):
        item = mylist[i]
        if item in counts and counts[item]:
            mylist[i] += str(counts[item])
            counts[item]-=1
    print(mylist)
    
    # ['name1', 'state', 'name2', 'city', 'name3', 'zip1', 'zip2']
    

    This should be O(n).

    Other provided answers:

    mylist.index(s) per element causes O(n^2)

    mylist = ["name", "state", "name", "city", "name", "zip", "zip"]
    
    from collections import Counter
    counts = Counter(mylist)
    for s,num in counts.items():
        if num > 1:
            for suffix in range(1, num + 1):
                mylist[mylist.index(s)] = s + str(suffix) 
    

    count(x[1]) per element causes O(n^2)
    It is also used multiple times per element along with list slicing.

    print map(lambda x: x[1] + str(mylist[:x[0]].count(x[1]) + 1) if mylist.count(x[1]) > 1 else x[1], enumerate(mylist))
    

    Benchmarks:

    http://nbviewer.ipython.org/gist/dting/c28fb161de7b6287491b

    0 讨论(0)
提交回复
热议问题