Python 中的列表推导式是否会以内存有效的方式减少?
我是 Python 初学者,这是我的第一篇文章,所以不要太严厉:)。我最近一直在玩Python,想知道类似的事情
max([x for x in range(25)])
是否会导致Python首先创建所有元素的列表,然后找到最大值,从而导致O(2n)时间,或者它会跟踪最大值它正在迭代 θ(n)。另外,由于 Python3 中的范围不同(可迭代),这会使其与 Python2 中的范围不同吗?
I am a beginner at Python, and this is my first post, so don't be too harsh :). I've been playing around with Python lately and was wondering if something like
max([x for x in range(25)])
would result in Python first creating a list of all the elements and then finding the max, resulting in O(2n) time, or it would keep track of the max as it was iterating for Θ(n). Also, since range differs in Python3 (being a iterable), would that make it different than in Python2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的示例将导致 Python 首先构建整个列表。如果你想避免这种情况,你可以使用生成器表达式来代替:
或者简单地:
当然(在Python 2中),
range
本身构建了一个完整的列表,所以在这种情况下你真正想要的是:然而,就所花费的时间而言,所有这些表达式都具有相同的复杂性。重要的区别是最后一个需要 O(1) 空间,而其他需要 O(n) 空间。
Your example will result in Python first building the entire list. If you want to avoid that, you can use a generator expression instead:
or simply:
Of course (in Python 2),
range
itself builds an entire list, so what you really want in this case is:However, regarding the time taken, all these expressions have the same complexity. The important difference is that the last one requires O(1) space, whereas the others require O(n) space.
列表推导式总是生成一个列表(除非抛出异常)。在大多数情况下,建议使用genex。
List comprehensions always generate a list (unless something throws an exception). Use of a genex instead is recommended in most cases.