A faster method to generate a nested list from a template?
Jeff Epler
jepler at unpythonic.net
Wed May 4 10:21:18 EDT 2005
Are there only a few, unchanging templates? If so, (dynamiclly) create
a function for each template. This will be nearly the fastest you can
go in Python, excluding the time to create and byte-compile the nesting
function.
# This code is in the public domain
def make_nesting_expression(l, s):
result = []
for c in l:
if isinstance(c, list):
sub, s = make_nesting_expression(c, s)
result.append(sub)
else:
result.append("l[%d]" % s)
s += 1
print "make_nesting_expression", l, result
return "[" + ",".join(result) + "]", s
def make_nesting_function(l):
return eval("lambda l: %s" % make_nesting_expression(l, 0)[0])
t = [['a1','a2'],['b1'],['c1'],['d1']]
l = [1, 2, 3, 4, 5]
f = make_nesting_function(t)
print f(l)
Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050504/2dd7f671/attachment.sig>
More information about the Python-list
mailing list