我编写了两个函数f和g,它们的功能相同。
def f(l, count):
if count > 1:
for i in f(l, count-1):
yield i + 1
else:
yield from l
for i in f(range(100000),900):
pass
print('f')
并且
def g(l, count):
if count > 1:
tmp = []
for i in g(l, count-1):
tmp.append(i+1)
return tmp
else:
return l
for i in g(range(100000),900):
pass
print('f')
我认为f应该更快,但实际运行时g更快。
g的时间更短。
real 0m5.977s
user 0m5.956s
sys 0m0.020s
时间到了
real 0m7.389s
user 0m7.376s
sys 0m0.012s
timeit
模块应该会给你更精确的结果。另外,在else
部分,你做了两件完全不同的事情!在g
中,你只是返回列表l
的引用;在f
中,你遍历列表并逐个yield
每个项目。还有,你的输入列表l
是什么? - hiro protagonistfor i in h(...
应该是f
,而不是h
。当我更正这个错误并在我的电脑上运行代码时,我得到了与你得到的相反的结果。 - Dunesyield from
迭代器。 - hiro protagonist