mag_list = filter(lambda x: x != 99, var_s[4::3])
好的,这里有一些timeit
试验,都在 Python 2.7.2 中:
设置:
>>> from random import seed, random
>>> from timeit import Timer
>>> from itertools import islice, ifilter, imap
>>> seed(1234); var_s = [random() for _ in range(100)]
使用 for 循环:
>>> def using_for_loop():
... mag_list = []
... for j in xrange(4, len(var_s), 3):
... value = float(var_s[j])
... if value != 99: mag_list.append(value)
...
>>> Timer(using_for_loop).timeit()
11.596584796905518
使用地图和过滤器:
>>> def using_map_filter():
... map(float, filter(lambda x: x != 99, var_s[4::3]))
...
>>> Timer(using_map_filter).timeit()
8.643505096435547
使用 islice、imap、ifilter:
>>> def using_itertools():
... list(imap(float, ifilter(lambda x: x != 99, islice(var_s, 4, None, 3))))
...
>>> Timer(using_itertools).timeit()
11.311019897460938
使用列表推导和 islice:
>>> def using_list_comp():
... [float(v) for v in islice(var_s, 4, None, 3) if v != 99]
...
>>> Timer(using_list_comp).timeit()
8.52650499343872
>>>
总之,使用带有 islice 的列表推导是最快的,其次是使用 map 和 filter 稍慢一些。