<pre><code>[str(wi) for wi in wordids]
</code></pre>
<p>是一个<strong><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a></strong>。</p>
<pre><code>a = [str(wi) for wi in wordids]
</code></pre>
<p>与</p>
<pre><code>a = []
for wi in wordids:
a.append(str(wi))
</code></pre>
<p>所以</p>
<pre><code>createkey='_'.join(sorted([str(wi) for wi in wordids]))
</code></pre>
<p>从<code>wordids</code>中的每个项创建一个字符串列表,然后对该列表进行排序,并使用<code>_</code>作为分隔符将其连接到一个大字符串中。</p>
<p>正如agf所正确指出的,您还可以使用生成器表达式,它看起来就像一个列表理解,但是带有括号而不是括号。如果以后不需要列表,这可以避免构建列表(除了迭代它)。如果你已经有了括号,就像这里的<code>sorted(...)</code>一样,你可以简单地删除括号。</p>
<p>但是,在这种特殊情况下,您不会获得性能优势(实际上,它会慢10%左右;我对它进行了计时),因为<code>sorted()</code>无论如何都需要构建一个列表,但看起来更好一些:</p>
<pre><code>createkey='_'.join(sorted(str(wi) for wi in wordids))
</code></pre>
<hr/>
<pre><code>normalizedscores = dict([(u,float(l)/maxscore) for (u,l) in linkscores.items()])
</code></pre>
<p>遍历字典<code>linkscores</code>中的项,其中每个项都是键/值对。它创建一个键/<code>l/maxscore</code>元组列表,然后将该列表转换回字典。</p>
<p>但是,自从Python 2.7以来,您还可以使用<strong><a href="http://docs.python.org/py3k/whatsnew/3.0.html#new-syntax" rel="noreferrer">dict comprehensions</a></strong>:</p>
<pre><code>normalizedscores = {u:float(l)/maxscore for (u,l) in linkscores.items()}
</code></pre>
<hr/>
<p>以下是一些计时数据:</p>
<p><strong>Python 3.2.2版</strong></p>
<pre><code>>>> 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
</code></pre>
<p><strong>Python 2.7.2版</p>
<pre><code>>>> 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
</code></pre>