Vectorizing A For Loop In Python
I'm a newbie to python and had a question to ask about vectorizing a code def makeNames2(nList): for nLi in nList: nLIdx=[i for i,j in enumerate(nList) if j==nLi] if nLId
Solution 1:
nLTest, items = ['asda','asda','test','ada','test','yuil','test'], {}
for idx, item inenumerate(nLTest):
nLTest[idx] += str(items.setdefault(item, 0) or"")
items[item] += 1print nLTest
Output
['asda', 'asda1', 'test', 'ada', 'test1', 'yuil', 'test2']
Solution 2:
You could 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] = 0return lst
This removes one of the for
loops, operating in O(n)
(dictionary access is O(1)
).
Note that this modifies the list in-place; you may wish to have a new output
list to append
to instead. You could also simplify this slightly using defaultdict
or Counter
from the collections
module.
Solution 3:
This is arguably more readable, avoids O(n^2)
. It's also not in-place.
from collections import defaultdict
defmakeNames3(nList):
counter= defaultdict(lambda:0)
defposfix(x):
n= counter[x]
counter[x]+=1returnstr(n) if n>0else""return [x+posfix(x) for x in nList]
Post a Comment for "Vectorizing A For Loop In Python"