비슷한 목록 필터링을 찾고 있었지만 여기에 제시된 것과 약간 다른 형식을 원했습니다.
위의 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의 솔루션 사이의 시간 차이는 아마 소음입니다. 그러나 나는 어떤 순서로든 필요한 모든 필터를 적용 할 수있는 유연성을 선호합니다.
실적이 걱정된다면 ** 실적 **을 테스트 했습니까? –
그것이 분명하지 않다고 생각한다면 나는 가질 것입니다. – cammil
"명백한"은 성능면에서 위험한 단어입니다. –