本文介绍了sorted() 使用生成器表达式而不是列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到这里的讨论后:Python - 生成时差 我很好奇.我最初也认为生成器比列表更快,但是说到 sorted() 我不知道.将生成器表达式发送到 sorted() 而不是列表有什么好处吗?无论如何,生成器表达式在排序之前最终会在 sorted() 中生成一个列表吗?

After seeing the discussion here: Python - generate the time difference I got curious. I also initially thought that a generator is faster than a list, but when it comes to sorted() I don't know. Is there any benefit to sending a generator expression to sorted() rather than a list? Does the generator expression end up being made into a list inside sorted() before sorting anyway?

我只能接受一个答案让我很伤心,因为我觉得很多回复都有助于澄清问题.再次感谢大家.

It grieves me to only be able to accept one answer, as I feel a lot of responses have helped to clarify the issue. Thanks again to everyone.

推荐答案

sorted() 做的第一件事就是将数据转换为列表.基本上实现的第一行(在参数验证之后)是

The first thing sorted() does is to convert the data to a list. Basically the first line (after argument validation) of the implementation is

newlist = PySequence_List(seq);

另见完整的源代码版本 2.73.1.2 版.

编辑:正如aaronasterling 的回答,变量 newlist 是一个 new 列表.如果参数已经是列表,则复制它.因此,生成器表达式确实具有使用更少内存的优势.

Edit: As pointed out in the answer by aaronasterling, the variable newlist is, well, a new list. If the parameter is already a list, it is copied. So a generator expression really has the advantage of using less memory.

这篇关于sorted() 使用生成器表达式而不是列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 21:21