What is the difference between `sorted(list)` vs `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() 当你想对一个可迭代的东西进行排序时,使用 还.
Use
list.sort()when you want to mutate the list,sorted()when you want a new sorted object back. Usesorted()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()` 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:`sorted(list)` 与 `list.sort()` 有什么区别?
基础教程推荐
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
