Skip to content

Instantly share code, notes, and snippets.

@tillahoffmann
Created March 6, 2012 14:35
Show Gist options
  • Save tillahoffmann/1986588 to your computer and use it in GitHub Desktop.
Save tillahoffmann/1986588 to your computer and use it in GitHub Desktop.
Merging lists based on elementwise comparison
import timeit
setup = '''
from random import Random
from itertools import izip
import numpy as np
length = 1000
random = Random()
A_new = np.array([random.random() for _ in xrange(length)])
A_old = np.array([random.random() for _ in xrange(length)])
B_new = np.array(range(length))
B_old = np.array([length - x for x in xrange(length)])
'''
naive = '''
for i, (a_new, a_old) in enumerate(izip(A_new, A_old)):
if a_new > a_old:
B_old[i] = B_new[i]
'''
mapping = '''
B_old = map(lambda (a_new, a_old, b_new, b_old): b_new if a_new > a_old else b_old,
izip(A_new, A_old, B_new, B_old))
'''
kev = '''
B_old = [B_new[i] if A_new[i]>A_old[i] else B_old[i] for i in range(len(A_old))]
'''
booleanarray = '''
arr = A_new > A_old
B_old[arr] = B_new[arr]
'''
where = '''
B_old = np.where(A_new > A_old, B_new, B_old)
'''
number = 1000
print 'Naive:', timeit.timeit(naive, setup, number = number)
print 'Mapping:', timeit.timeit(mapping, setup, number = number)
print 'kev:', timeit.timeit(kev, setup, number = number)
print 'Numpy:', timeit.timeit(booleanarray, setup, number = number)
print 'Where:', timeit.timeit(where, setup, number = number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment