Last active
October 1, 2015 17:35
-
-
Save jvanasco/8793879 to your computer and use it in GitHub Desktop.
different ways of handling a filtered list comprehension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import timeit | |
## http://stackoverflow.com/questions/21538689/python-are-there-other-ways-to-apply-a-function-and-filter-in-a-list-comprehen | |
words = [ 'one','two','three','',' four','five ','six','seven','eight ',' nine','ten',''] | |
def comprehension_double_strip(): | |
_words = [ w.strip() for w in words if w.strip() ] | |
def comprehension_two_lists(): | |
_words = [ w.strip() for w in words ] | |
_words = [ w for w in _words if w ] | |
def comprehension_inner_list(): | |
## [(x, y) for x in range(1, 5) for y in range(0, x)] | |
_words = [ i for i in [ w.strip() for w in words ] if i ] | |
def comprehension_generator(): | |
_words = [ i for i in ( w.strip() for w in words ) if i ] | |
def comprehension_filter(): | |
cleaned = filter(None, map(str.strip, words)) | |
def comprehension_map(): | |
cleaned = [i for i in map(str.strip, words) if i] | |
def templist(): | |
cleaned = [stripped for word in words | |
for stripped in [word.strip()] | |
if stripped] | |
iterations = 10000 | |
time_a = timeit.timeit('comprehension_double_strip()','from __main__ import comprehension_double_strip , words', number=iterations) | |
time_b = timeit.timeit('comprehension_two_lists()','from __main__ import comprehension_two_lists , words', number=iterations) | |
time_c = timeit.timeit('comprehension_inner_list()','from __main__ import comprehension_inner_list , words', number=iterations) | |
time_d = timeit.timeit('comprehension_generator()','from __main__ import comprehension_generator , words', number=iterations) | |
time_e = timeit.timeit('comprehension_filter()','from __main__ import comprehension_filter , words', number=iterations) | |
time_f = timeit.timeit('comprehension_map()','from __main__ import comprehension_map , words', number=iterations) | |
time_g = timeit.timeit('templist()','from __main__ import templist , words', number=iterations) | |
print "comprehension_double_strip- %s" % time_a | |
print "comprehension_two_lists - %s" % time_b | |
print "comprehension_inner_list - %s" % time_c | |
print "comprehension_generator - %s" % time_d | |
print "comprehension_filter - %s" % time_e | |
print "comprehension_map - %s" % time_f | |
print "templist - %s" % time_g |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment