Vectorizing a for loop in python

I am new to python and asked a question about code vectorization

def makeNames2(nList):
  for nLi in nList:
    nLIdx=[i for i,j in enumerate(nList) if j==nLi]
    if nLIdx.__len__()>1:
        for i,j in enumerate(nLIdx):
            if i>0: nList[j]=nList[j]+str(i)
  return nList

which performs the following actions:

>>> nLTest=['asda','asda','test','ada','test','yuil','test']
>>> print(makenames2(nLTest)
['asda', 'asda1', 'test', 'ada', 'test1', 'yuil', 'test2']

The code works fine, but I was wondering if there is a way to vectorize the loops for?

EDIT

Thanks to all for all three answers. This is exactly what interests me and I would like to select all the answers. I can not choose more than one, but they all work.

+3
source share
3 answers
nLTest, items = ['asda','asda','test','ada','test','yuil','test'], {}
for idx, item in enumerate(nLTest):
    nLTest[idx] += str(items.setdefault(item, 0) or "")
    items[item] += 1
print nLTest

Output

['asda', 'asda1', 'test', 'ada', 'test1', 'yuil', 'test2']
+3
source

You can simplify it a bit:

def makenames(lst):
    seen = {}
    for index, name in enumerate(lst):
        if name in seen:
            seen[name] += 1
            lst[index] = "{0}{1}".format(name, seen[name])
        else:
            seen[name] = 0
    return lst

This removes one of the loops forworking in O(n)(dictionary access - O(1)).

, ; output append. , defaultdict Counter collections.

+1

It is perhaps more readable, avoids O(n^2). It is also out of place.

from collections import defaultdict
def makeNames3(nList):
    counter= defaultdict(lambda:0)
    def posfix(x):
        n= counter[x]
        counter[x]+=1
        return str(n) if n>0 else ""
    return [x+posfix(x) for x in nList]
+1
source

All Articles