<p><code>list.sort()</code>对列表进行适当排序并返回<code>None</code>,因此实际上是将返回值赋给<code>List1</code>,即<code>None</code>。在</p>
<pre><code>>>> List1 =[7,6,9]
>>> repr(List1.sort())
'None' #return Value of list.sort
>>> List1 #though list is sorted
[6, 7, 9]
</code></pre>
<p>另一方面,内置函数<code>sorted</code>返回一个<strong>新的</strong>排序列表:</p>
^{pr2}$
<p>您可以将<code>sorted</code>的结果分配给<code>List1</code>,但这没有意义,因为{<cd8>}将在更短的时间内完成相同的操作。在</p>
<pre><code>>>> List1 = sorted(List1)
>>> List1
[6, 7, 9]
</code></pre>
<p>虽然上面的代码类似于<code>list.sort</code>,但实际上它有点不同,因为它返回新的list。示例:</p>
<pre><code>>>> List1 =[7,6,9]
>>> List2 = List1 # both List1, List2 point to the same object [7, 6, 9]
>>> List1.sort() # sort List1 in-place, affects the original object
>>> List1, List2
([6, 7, 9], [6, 7, 9]) # both variables still point to the same list
>>> List1 =[7,6,9]
>>> List2 = List1 #same as above
>>> List1 = sorted(List1) #sorted returns a new list, so List1 now points to this new list
>>> List1, List2 #List2 is still unchanged
([6, 7, 9], [7, 6, 9])
</code></pre>
<p>时间比较:</p>
<pre><code>>>> from random import shuffle
>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit lis.sort()
1 loops, best of 3: 9.9 ms per loop
>>> lis = range(10**5)
>>> shuffle(lis)
>>> %timeit sorted(lis)
1 loops, best of 3: 95.9 ms per loop
</code></pre>
<p>因此,<code>sorted</code>应该只在您不想影响原始列表并希望将该列表的排序版本分配给其他变量时使用。在</p>
<p>除了列出其他数据结构,如<strong>set</strong>,<strong>元组</strong>,<strong>dicts</strong>等等,没有它们自己的<code>.sort()</code>方法,因此<code>sorted</code>是唯一可以在那里使用的东西。在</p>
<pre><code>>>> s = {1,5,3,6} # set
>>> sorted(s)
[1, 3, 5, 6]
</code></pre>
<p>关于<code>sorted</code>的帮助:</p>
<pre><code>>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) > new sorted list
</code></pre>