生成器函数的效率可能低于直接构建列表。
您可以在holes_between()
函数中构建列表并返回:
def holes_between(intervals):
prec = intervals[0][1] + 1 # Bootstrap the iteration
result = []
for low, high in intervals[1:]:
if prec <= low - 1:
result.append((prec, low - 1))
prec = high + 1
return result
但请使用模块测量差异。timeit
如果您有一些典型的输入,您可以使用以下方法进行测试:
import timeit
def holes_between_list(intervals):
prec = intervals[0][1] + 1 # Bootstrap the iteration
result = []
for low, high in intervals[1:]:
if prec <= low - 1:
result.append((prec, low - 1))
prec = high + 1
return result
def holes_between_generate(intervals):
prec = intervals[0][1] + 1 # Bootstrap the iteration
for low, high in intervals[1:]:
if prec <= low - 1:
yield (prec, low - 1)
prec = high + 1
intervals = [ ... ] # fill in some test data
print 'As list:', timeit.timeit(
'holes_between(intervals)',
'from __main__ import intervals, holes_between_list as holes_between')
print 'Using a generator:', timeit.timeit(
'list(holes_between(intervals))',
'from __main__ import intervals, holes_between_generate as holes_between')
较低的值是测试数据的更快方法。