`sorted(list)` 和 `list.sort()` 有什么区别?

`sorted(list)` 和 `list.sort()` 有什么区别?

问题描述:

list.sort() 对列表进行排序并替换原始列表,而 sorted(list) 返回列表的排序副本,而不更改原始列表.

list.sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list.

  • 什么时候更喜欢一个?
  • 哪个更有效?多少钱?
  • 执行list.sort() 后,列表是否可以恢复为未排序状态?
  • When is one preferred over the other?
  • Which is more efficient? By how much?
  • Can a list be reverted to the unsorted state after list.sort() has been performed?

sorted() 返回一个 new 排序列表,原始列表不受影响.list.sort() 对列表进行就地排序,改变列表索引,并返回None(就像所有就地操作一样).

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

sorted() 适用于任何可迭代对象,而不仅仅是列表.字符串、元组、字典(你会得到键)、生成器等,返回一个包含所有元素的列表,排序.

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.

  • 当你想要改变列表时使用 list.sort(),当你想要一个新的排序对象返回时使用 sorted().当您想对可迭代的内容而不是列表进行排序时,请使用 sorted().yet.

  • 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.

对于列表,list.sort()sorted() 快,因为它不必创建副本.对于任何其他可迭代对象,您别无选择.

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.

不,您无法检索原始位置.一旦你调用了 list.sort(),原来的顺序就消失了.

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