is there a better way...
Mark McEahern
marklists at mceahern.com
Fri May 10 11:48:00 EDT 2002
[Christopher Encapera]
> Subject: is there a better way...
>
>
> to loop over a list and replace an element based on its value than:
There are three ways shown below, including your approach (replace). Try
the script and see for yourself how each performs:
#! /usr/bin/env python
from time import clock
import random
def replace(l, old, new):
# Make a copy.
x = list(l)
y = len(x)
z = 0
while z < y:
element = x[z]
if element == old: x[z] = new
z = z +1
return x
def replace_for(l, old, new):
# Make a copy.
x = list(l)
for i in range(len(x)):
if x[i] == old:
x[i] = new
break # use continue if we expect more than one match.
return x
def replace_dict(l, old, new):
d = dict(zip(l, l))
d[old] = new
return d.values()
def timeit(f, *args):
time_in = clock()
result = f(*args)
time_out = clock()
return result, time_out - time_in
size = 100000
x = range(size)
old = random.randrange(0, size)
new = "blueberry"
r1, t1 = timeit(replace, x, old, new)
r2, t2 = timeit(replace_dict, x, old, new)
r3, t3 = timeit(replace_for, x, old, new)
assert(r1==r2==r3)
print "replace: %0.3f" % t1
print "replace_dict: %0.3f" % t2
print "replace_for: %0.3f" % t3
More information about the Python-list
mailing list