sorted(list)和list.sort()有什么区别? [英] What is the difference between `sorted(list)` vs `list.sort()`?

查看:108
本文介绍了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().

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

这篇关于sorted(list)和list.sort()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆