Estaba buscando un filtrado similar de listas, pero quería tener un formato ligeramente diferente al presentado aquí.
La llamada anterior get_hats()
es buena pero limitada en su reutilización. Estaba buscando algo más como get_hats(get_clothes(all_things))
, donde puede especificar una fuente (all_things)
, y luego el número de filtros get_hats()
, get_clothes()
que desee.
he encontrado una manera de hacer eso con generadores:
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
Esto entonces se puede llamar:
get_hats(get_clothes(all_things))
Probé las soluciones originales, la solución de VarTec y esta solución adicional para ver la eficiencia, y estaba algo sorprendido por los resultados. Código de la siguiente manera:
instalación:
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
soluciones originales:
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)
Mi solución: solución
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
de 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
código
Tiempo:
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)
Resultados:
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
El generador de expresiones parecen ser ligeramente más rápido, la diferencia en el tiempo entre mi y soluciones de VarTec son probablemente sólo ruido. Pero prefiero la flexibilidad de poder aplicar los filtros requeridos en cualquier orden.
Si le preocupa el rendimiento, ¿** evaluó ** el rendimiento? –
Lo habría hecho si hubiera pensado que no era obvio. – cammil
"obvio" es una palabra peligrosa cuando se trata de rendimiento. –