56 1449 119508 7 url

为什么 "1000000000000000 in range(1000000000000001)" 在 Python3 里速度那么快?

``````1000000000000000 in range(1000000000000001)
``````

``````000000000000000000000 in range(0,1000000000000000000001,10) # count by tens
``````

``````def my_crappy_range(N):
i = 0
while i < N:
yield i
i += 1
return
``````

Python3 的 `range()` 对象并不会立即产生数值;它会在需要时来产生.它包含你的起始, 终止和步长, 它会随着每次迭代来产生下一个数值.

`range` 优于于 `list``tuple` 的地方在于不管它的范围是多少它只占用少量的内存(因为它只保存 `start`, `stop`, `step`, 按需得到数值)

``````class my_range(object):
def __init__(self, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
self.start, self.stop, self.step = start, stop, step
if step < 0:
lo, hi = stop, start
else:
lo, hi = start, stop
self.length = ((hi - lo - 1) // abs(step)) + 1

def __iter__(self):
current = self.start
if self.step < 0:
while current > self.stop:
yield current
current += self.step
else:
while current < self.stop:
yield current
current += self.step

def __len__(self):
return self.length

def __getitem__(self, i):
if i < 0:
i += self.length
if 0 <= i < self.length:
return self.start + i * self.step
raise IndexError('Index out of range: {}'.format(i))

def __contains__(self, num):
if self.step < 0:
if not (self.stop < num <= self.start):
return False
else:
if not (self.start <= num < self.stop):
return False
return (num - self.start) % self.step == 0
``````