如果我已经正确理解了您想要的内容,那么以下内容将做到这一点:
import functools
import operator
L = list('abcd')
def foo(indexable):
return functools.partial(operator.__getitem__, indexable)
g = foo(L)
for i in xrange(len(L)):
print g(i),
更新:
我进行了进一步的实验,并惊讶地发现了一个稍微快一点的解决方案,这只不过是这个:
def foo2(indexable):
return indexable.__getitem__
当使用我拼凑的一个小测试台运行时,产生了以下结果:
fastest to slowest *_test() function timings:
10,000 elements, 1,000 timeit calls, best of 3
foo2_test() : 1.46 (0.00 times slower)
lambda_test() : 4.15 (1.84 times slower)
foo_test() : 4.28 (1.93 times slower)
使用的每个测试函数只是使用不同的技术在紧密循环中访问列表的每个元素。
好奇这如何应用于您对链接问题的排序答案,我使用它对列表进行排序而不是仅访问列表的每个元素一次,获得了这些不同的结果:
fastest to slowest *_test() function timings:
10,000 elements, 1,000 timeit calls, best of 3
foo2_test() : 13.03 (0.00 times slower)
foo_test() : 14.70 (0.13 times slower)
lambda_test() : 16.25 (0.25 times slower)
虽然foo2()
在这两种情况下都是最快的,但在排序版本中它只是很小的一部分。
以下是用于获取第一组结果以进行简单访问的完整测试平台的列表:
import functools
import operator
import timeit
import types
N = 1000
R = 3
SZ = 10000
SUFFIX = '_test'
SUFFIX_LEN = len(SUFFIX)
def setup():
import random
global a_list
a_list = [random.randrange(100) for _ in xrange(SZ)]
def lambda_test():
global a_list
f = lambda i: a_list[i]
for i in xrange(len(a_list)): f(i)
def foo(indexable):
return functools.partial(operator.__getitem__, indexable)
def foo_test():
global a_list
g = foo(a_list)
for i in xrange(len(a_list)): g(i)
def foo2(indexable):
return indexable.__getitem__
def foo2_test():
global a_list
g = foo2(a_list)
for i in xrange(len(a_list)): g(i)
# find all the functions named *SUFFIX in the global namespace
funcs = tuple(value for id,value in globals().items()
if id.endswith(SUFFIX) and type(value) is types.FunctionType)
# run the timing tests and collect results
timings = [(f.func_name[:-SUFFIX_LEN],
min(timeit.repeat(f, setup=setup, repeat=R, number=N))
) for f in funcs]
timings.sort(key=lambda x: x[1]) # sort by speed (ironic use of lambda?)
fastest = timings[0][1] # time fastest one took to run
longest = max(len(t[0]) for t in timings) # len of longest func name (w/o suffix)
print 'fastest to slowest *_test() function timings:\n' \
' {:,d} elements, {:,d} timeit calls, best of {:d}\n'.format(SZ, N, R)
def times_slower(speed, fastest):
return speed/fastest - 1.0
for i in timings:
print "{0:>{width}}{suffix}() : {1:.2f} ({2:.2f} times slower)".format(
i[0], i[1], times_slower(i[1], fastest), width=longest, suffix=SUFFIX)
这是测试排序用法时不同的部分:
def setup():
import random
global a_list
a_list = [random.randrange(100) for _ in xrange(SZ)]
def lambda_test():
global a_list
sorted(range(len(a_list)), key=lambda i:a_list[i])
def foo(indexable):
return functools.partial(operator.__getitem__, indexable)
def foo_test():
global a_list
sorted(range(len(a_list)), key=foo(a_list))
def foo2(indexable):
return indexable.__getitem__
def foo2_test():
global a_list
sorted(range(len(a_list)), key=foo2(a_list))