问题描述
在这里看到讨论后: 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.7 和版本3.1.2 .
编辑:如,那么变量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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!