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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22442378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:57:22  来源:igfitidea点击:

What is the difference between `sorted(list)` vs `list.sort()`?

pythonlistsortingcopyin-place

提问by alvas

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()对列表进行排序并替换原始列表,而sorted(list)返回列表的排序副本,而不更改原始列表。

  • 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?
  • 什么时候一个比另一个更受欢迎?
  • 哪个更有效率?到多少?
  • 列表list.sort()执行后可以恢复到未排序状态吗?

采纳答案by Martijn Pieters

sorted()returns a newsorted 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()返回一个新的排序列表,原始列表不受影响。就地list.sort()对列表进行排序,改变列表索引,然后返回None(就像所有就地操作一样)。

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.

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.

  • list.sort()当你想要改变列表sorted()时使用,当你想要一个新的排序对象时使用。使用sorted()时要排序的东西,是一个可迭代,而不是一个名单尚未

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

  • 不,您无法检索原始位置。一旦你调用list.sort()了原来的命令就没有了。

回答by Christian

The main difference is that sorted(some_list)returns a new list:

主要区别在于sorted(some_list)返回一个新的list

a = [3, 2, 1]
print sorted(a) # new list
print a         # is not modified

and some_list.sort(), sorts the list in place:

some_list.sort()对列表进行排序

a = [3, 2, 1]
print a.sort() # in place
print a         # it's modified

Notethat since a.sort()doesn't return anything, print a.sort()will print None.

请注意,由于a.sort()不返回任何内容,因此print a.sort()将打印None.



Can a list original positions be retrieved after list.sort()?

list.sort() 后可以检索列表原始位置吗?

No, because it modifies the original list.

不,因为它修改了原始列表。

回答by Aaron Hall

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

sorted(list)vs 和有什么不一样list.sort()

  • list.sortmutates the list in-place & returns None
  • sortedtakes any iterable & returns a new list, sorted.
  • list.sort就地改变列表并返回 None
  • sorted接受任何迭代并返回一个新的列表,排序。

sortedis equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

sorted等效于这个 Python 实现,但 CPython 内置函数的运行速度应该明显更快,因为它是用 C 编写的:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

什么时候使用哪个?

  • Use list.sortwhen you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sortedwhen you want to retain the original sort order or when you wish to create a new list that only your local code owns.
  • 使用list.sort时,你不希望保留原来的排序顺序(这样你就可以重新使用内存就地列表。)当你在列表的唯一所有者(如果该名单是由其他代码和你共享对其进行变异,您可以在使用该列表的地方引入错误。)
  • 使用sorted时要创建一个新的列表,只有本地代码拥有,当你想保留原来的排序顺序或。

Can a list's original positions be retrieved after list.sort()?

在 list.sort() 之后可以检索列表的原始位置吗?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

否 - 除非您自己制作副本,否则该信息会丢失,因为排序是就地完成的。

"And which is faster? And how much faster?"

“哪个更快?快多少?”

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

为了说明创建新列表的代价,使用 timeit 模块,这是我们的设置:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

这是我们对随机排列的 10000 个整数的列表的结果,正如我们在这里看到的,我们已经推翻了一个旧的列表创建费用神话

Python 2.7

蟒蛇 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

蟒蛇 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]


After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

经过一些反馈,我决定进行另一项具有不同特征的测试。在这里,我为每次迭代 1,000 次提供相同的随机排序列表,长度为 100,000。

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

我将这种更大的差异解释为来自 Martijn 提到的复制,但它并没有达到此处较旧的更流行答案中所述的程度,这里的时间增加仅约 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sortedcopy version still takes about 2% longer running time on a sort of 1000 length.

我还在更小的排序上运行了上面的代码,发现新的sorted副本版本在 1000 长度的排序上仍然需要大约 2% 的运行时间。

Poke ran his own code as well, here's the code:

Poke 也运行了自己的代码,代码如下:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

他发现对于 1000000 长度的排序,(运行 100 次)类似的结果,但只增加了大约 5% 的时间,这是输出:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

结论:

A large sized list being sorted with sortedmaking a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sortedwhen I need a new sorted list of the data, and I would use list.sortwhen I need to sort a list in-place, and let that determine my usage.

通过sorted复制对大型列表进行排序可能会主导差异,但排序本身主导操作,围绕这些差异组织代码将是过早的优化。我会用sorted我所需要的数据的新排序列表,我会用list.sort我需要梳理就地名单,并让这决定我的使用。

回答by Vicrobot

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

.sort() 函数将新列表的值直接存储在列表变量中;所以你的第三个问题的答案是否定的。此外,如果您使用 sorted(list) 执行此操作,则可以使用它,因为它未存储在列表变量中。有时 .sort() 方法也充当函数,或者说它在其中接受参数。

You have to store the value of sorted(list) in a variable explicitly.

您必须将 sorted(list) 的值显式存储在变量中。

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

同样对于短数据处理,速度也没有区别;但对于长列表;您应该直接使用 .sort() 方法进行快速工作;但你将再次面临不可逆转的行动。

回答by Stryker

Here are a few simple examples to see the difference in action:

以下是一些简单的示例,可以查看操作上的差异:

See the list of numbers here:

请参阅此处的数字列表:

nums = [1, 9, -3, 4, 8, 5, 7, 14]

When calling sortedon this list, sortedwill make a copyof the list. (Meaning your original list will remain unchanged.)

在调用sorted此列表时,sorted将制作该列表的副本。(这意味着您的原始列表将保持不变。)

Let's see.

让我们来看看。

sorted(nums)

returns

返回

[-3, 1, 4, 5, 7, 8, 9, 14]

Looking at the numsagain

纵观nums再次

nums

We see the original list (unaltered and NOT sorted.). sorteddid not change the original list

我们看到原始列表(未更改且未排序。)。sorted没有改变原来的清单

[1, 2, -3, 4, 8, 5, 7, 14]

Taking the same numslist and applying the sortfunction on it, will change the actual list.

获取相同的nums列表并对其应用sort函数,将更改实际列表。

Let's see.

让我们来看看。

Starting with our numslist to make sure, the content is still the same.

从我们的nums列表开始,以确保内容仍然相同。

nums

[-3, 1, 4, 5, 7, 8, 9, 14]

nums.sort()

Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.

现在原始 nums 列表已更改,查看 nums 我们看到原始列表已更改并且现在已排序。

nums
[-3, 1, 2, 4, 5, 7, 8, 14]

回答by Projesh Bhoumik

Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

注意: sort() 和 sorted() 之间最简单的区别是: sort() 不返回任何值,而 sorted() 返回一个可迭代列表。

sort() doesn't return any value.

sort() 不返回任何值。

The sort() method just sorts the elements of a given list in a specific order - Ascending or Descending without returning any value.

sort() 方法只是按特定顺序对给定列表的元素进行排序 - 升序或降序,而不返回任何值。

The syntax of sort() method is:

sort() 方法的语法是:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted function return sorted list

或者,您也可以将 Python 的内置函数 sorted() 用于相同目的。排序函数返回排序列表

 list=sorted(list, key=..., reverse=...)