[str(wi) for wi in wordids]
is > .
a = [str(wi) for wi in wordids]
coincides with
a = [] for wi in wordids: a.append(str(wi))
So
createkey='_'.join(sorted([str(wi) for wi in wordids]))
creates a list of strings from each element in wordids
, then sorts this list and wordids
it to the large string, using _
as the delimiter.
As correctly noted, you can also use a generator expression that looks exactly like a list comprehension, but with parentheses instead of brackets. This avoids creating a list unless you need it later (with the exception of repeating it). And if you already have parentheses, as in this case with sorted(...)
, you can just remove the parentheses.
However, in this special case, you will not get a performance gain (in fact, it will be about 10% slower, I dated it), because sorted()
will have to create a list anyway, but it looks a little nicer:
createkey='_'.join(sorted(str(wi) for wi in wordids))
normalizedscores = dict([(u,float(l)/maxscore) for (u,l) in linkscores.items()])
linkscores
over the elements of the linkscores
dictionary, where each element is a key / value pair. It creates a list of key / l/maxscore
, and then returns that list to the dictionary.
However, since Python 2.7, you can also use dict solutions :
normalizedscores = {u:float(l)/maxscore for (u,l) in linkscores.items()}
Here are some temporary data:
Python 3.2.2
>>> import timeit >>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]") 61.37724242267409 >>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]") 66.01814811313774
Python 2.7.2
>>> import timeit >>> timeit.timeit(stmt="a = '_'.join(sorted([str(x) for x in n]))", setup="import random; n = [random.randint(0,1000) for i in range(100)]") 58.01728623923137 >>> timeit.timeit(stmt="a = '_'.join(sorted(str(x) for x in n))", setup="import random; n = [random.randint(0,1000) for i in range(100)]") 60.58927580777687