纯粹出于好奇,我将自己的答案与您的原始代码和 F.J. 的解决方案相结合,以进行性能对比测试。
您的解决方案似乎是所有解决方案中最快的。我的解决方案检查控件元组的所有可能元素,因此随着元组大小的增加它会变慢。
代码如下:
from timeit import Timer as T
from itertools import chain, dropwhile
class control(object):
def __init__(self, name):
self.name = name
def johan_venge(tuple_):
for el in tuple_:
if el.name == 'foobar':
return el
return None
def mac(tuple_):
return filter(lambda x : x.name == 'foobar', tuple_)[0]
def mac2(tuple_):
return list(dropwhile(lambda x : x.name != 'foobar', tuple_))[0]
def fj(tuple_):
return next(c for c in tuple_ if c.name == 'foobar')
def fj2(tuple_):
return next(chain((c for c in tuple_ if c.name == 'foobar')))
if __name__ == '__main__':
REPS = 10000
controls = (control('hello'), control('world'), control('foobar'))
print T(lambda : johan_venge(controls)).repeat(number = REPS)
print T(lambda : mac(controls)).repeat(number = REPS)
print T(lambda : mac2(controls)).repeat(number = REPS)
print T(lambda : fj(controls)).repeat(number = REPS)
print T(lambda : fj2(controls)).repeat(number = REPS)
这是我系统上的输出:
[0.005961179733276367, 0.005975961685180664, 0.005918025970458984]
[0.013427019119262695, 0.013586044311523438, 0.013450145721435547]
[0.024325847625732422, 0.0254058837890625, 0.02396702766418457]
[0.014491081237792969, 0.01442408561706543, 0.01484990119934082]
[0.01691603660583496, 0.016616106033325195, 0.016437053680419922]
HTH! :)