8

我是 Python 的初学者,这是我的第一篇文章,所以不要太苛刻:)。我最近一直在玩 Python,想知道是否有类似的东西

max([x for x in range(25)]) 

将导致 Python 首先创建所有元素的列表,然后找到最大值,从而导致 O(2n) 时间,或者它会在迭代 Θ(n) 时跟踪最大值。此外,由于 Python3 中的范围不同(作为可迭代对象),这会使其与 Python2 中的不同吗?

4

2 回答 2

14

Your example will result in Python first building the entire list. If you want to avoid that, you can use a generator expression instead:

max((x for x in range(25)))

or simply:

max(x for x in range(25))

Of course (in Python 2), range itself builds an entire list, so what you really want in this case is:

max(x for x in xrange(25))

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.

于 2011-03-18T08:52:21.530 回答
2

List comprehensions always generate a list (unless something throws an exception). Use of a genex instead is recommended in most cases.

max(x for x in xrange(25))
于 2011-03-18T08:51:38.390 回答