比较如下:#!/usr/bin/python
import cProfile
from timeit import Timer
from faker import Faker
def longest1(lists):
return max(len(s) for s in lists)
def longest2(lists):
return len(max(lists, key=len))
def longest3(lists):
return len(sorted(lists, key=len)[-1])
s = Faker()
seq = [ s.word() for x in range(100) ]
func = [ longest1, longest2, longest3 ]
for f in func:
t = Timer(lambda: f(seq))
print f.__name__, cProfile.run('t.timeit(number=1000)')
结果:longest2最快
输出:
^{pr2}$