gpt4 book ai didi

python - Python 可以让列表更高效吗?

转载 作者:行者123 更新时间:2023-11-28 16:44:43 25 4
gpt4 key购买 nike

在 Python v2.7 中,如果我有这样的函数:

def holes_between(intervals):
# Compute the holes between the intervals, for example:
# given the intervals: ([ 8, 9] [14, 18] [19, 20] [23, 32] [34, 49])
# compute the holes: ([10, 13] [21, 22] [33, 33])
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

holes = list(holes_between(intervals))

由于函数的 yield 被收集到 list 中,在 holes_between 函数中构建列表是否更有效如果是这样,如何最有效地做到这一点?

最佳答案

与直接构建列表相比,生成器函数可能效率较低。

您可以在 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 module .

如果您有一些典型的输入,您可以使用以下方法进行测试:

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')

值越小,测试数据的方法越快

关于python - Python 可以让列表更高效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com