Skip to content

Instantly share code, notes, and snippets.

@dmedvinsky
Created August 13, 2012 13:36
Show Gist options
  • Save dmedvinsky/3340839 to your computer and use it in GitHub Desktop.
Save dmedvinsky/3340839 to your computer and use it in GitHub Desktop.
List comprehension, map-filter, custom loop, generator
from random import choice
from operator import methodcaller
l = []
for i in range(1000):
l.append(choice(['1', '10', '', ' ']))
def mapfilt(xs):
""" Test map-filter. """
return filter(bool, map(methodcaller('strip'), xs))
def listcomp(xs):
""" Test list comprehension. """
return [x.strip() for x in xs if x.strip()]
def gen(xs):
def f(xs):
for x in xs:
y = x.strip()
if y:
yield y
return list(f(xs))
def loop(xs):
""" Test append loop. """
ys = []
for x in xs:
y = x.strip()
if y:
ys.append(y)
return ys
dmedvinsky at zeus in ~
><((°> python2 -mtimeit -s'import filtermap' 'filtermap.loop(filtermap.l)'
1000 loops, best of 3: 265 usec per loop
dmedvinsky at zeus in ~
><((°> python2 -mtimeit -s'import filtermap' 'filtermap.listcomp(filtermap.l)'
1000 loops, best of 3: 221 usec per loop
dmedvinsky at zeus in ~
><((°> python2 -mtimeit -s'import filtermap' 'filtermap.gen(filtermap.l)'
1000 loops, best of 3: 209 usec per loop
dmedvinsky at zeus in ~
><((°> python2 -mtimeit -s'import filtermap' 'filtermap.mapfilt(filtermap.l)'
10000 loops, best of 3: 172 usec per loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment