Python | sorted() and sort()?

今天错了一道题,虽然不止这一道,但是这道题值得一提。由于自己平时学习的粗心而不注意一些细节问题,导致这样的简单错误,所谓千里之堤毁于蚁穴,小细节不容忽视。

其实是个很简单的问题, 给一个 list: a = [2, 2, 1, 1, 3, 3], 用 Python 简单返回去除重复值且排好序的 list: b

用 Python 要不要太简单!

1
2
3
4
5
6
7
In [5]: list(set(a).sort())
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-8adc4a635544> in <module>()
----> 1 list(set(a).sort())

AttributeError: 'set' object has no attribute 'sort'

heheda!

(⊙o⊙)… 那这样:

1
2
3
4
In [6]: b = list(set(a)).sort()

In [7]: b
None

( ⊙ o ⊙ )啊!

正确姿势应该是:

1
2
3
4
In [3]: b = sorted(set(a))

In [4]: b
Out[4]: [1, 2, 3]

问题在于

  1. sort() 只能用于 list, 对于其他的如 dict 只能用 sorted(dict);
  2. list.sort()in-place 的,返回 None, 而 sorted() 会复制原来的然后返回一个 list.

Stackoverflow:What is the difference between sorted(list) vs list.sort() ? python

sort() and sorted():

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices.

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you’ll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn’t have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.