我一直在寻找类似的列表过滤,但希望与此处显示的格式略有不同。
上面的get_hats() 调用很好,但重用性有限。我一直在寻找更像 get_hats(get_clothes(all_things)) 的东西,您可以在其中指定源 (all_things),然后根据需要指定尽可能少或尽可能多的过滤器级别 get_hats()、get_clothes()。
我找到了一种使用生成器的方法:
def get_clothes(in_list):
for item in in_list:
if item.garment:
yield item
def get_hats(in_list):
for item in in_list:
if item.headgear:
yield item
然后可以通过以下方式调用它:
get_hats(get_clothes(all_things))
我测试了原来的解决方案、vartec 的解决方案和这个附加的解决方案,看看效率,结果有点惊讶。代码如下:
设置:
class Thing:
def __init__(self):
self.garment = False
self.headgear = False
all_things = [Thing() for i in range(1000000)]
for i, thing in enumerate(all_things):
if i % 2 == 0:
thing.garment = True
if i % 4 == 0:
thing.headgear = True
原始解决方案:
def get_clothes():
return filter(lambda t: t.garment, all_things)
def get_hats():
return filter(lambda t: t.headgear, get_clothes())
def get_clothes2():
return filter(lambda t: t.garment, all_things)
def get_hats2():
return filter(lambda t: t.headgear and t.garment, all_things)
我的解决方案:
def get_clothes3(in_list):
for item in in_list:
if item.garment:
yield item
def get_hats3(in_list):
for item in in_list:
if item.headgear:
yield item
vartec 的解决方案:
def get_clothes4():
for t in all_things:
if t.garment:
yield t
def get_hats4():
for t in get_clothes4():
if t.headgear:
yield t
计时码:
import timeit
print 'get_hats()'
print timeit.timeit('get_hats()', 'from __main__ import get_hats', number=1000)
print 'get_hats2()'
print timeit.timeit('get_hats2()', 'from __main__ import get_hats2', number=1000)
print '[x for x in get_hats3(get_clothes3(all_things))]'
print timeit.timeit('[x for x in get_hats3(get_clothes3(all_things))]',
'from __main__ import get_hats3, get_clothes3, all_things',
number=1000)
print '[x for x in get_hats4()]'
print timeit.timeit('[x for x in get_hats4()]',
'from __main__ import get_hats4', number=1000)
结果:
get_hats()
379.334653854
get_hats2()
232.768362999
[x for x in get_hats3(get_clothes3(all_things))]
214.376812935
[x for x in get_hats4()]
218.250688076
生成器表达式似乎稍快一些,我的解决方案和 vartec 的解决方案之间的时间差异可能只是噪音。但我更喜欢能够以任何顺序应用所需过滤器的灵活性。