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

2022-01-20 00:00:00 python 复制 list sorting in-place

问题描述

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() 当你想对一个可迭代的东西进行排序时,使用 还.

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

相关文章