I thought that my earlier blog entry on emulating String.Format() in Python had some crufty code in it - specifically the code that expanded a list into a comma separated string. So after a bit of random reading in the Python Cookbook tonight, I discovered the map function.
It takes a function object as its first parameter, and list object as its second parameter. It calls the function for each member of the list and returns a new list containing the results of calling that function.
My original version of code looked like:
for n in argIndices:
expr += 'mo.group(%s), ' % n
My new version of code looks like:
groups = ','.join(map(lambda str: 'mo.group(%s)' % str, argIndices))
It also has the side-effect of not requiring the (A,B,) syntax for declaring tuples.
While this is arguably longer than my original version (in characters typed) - learning this technique lets me do a different optimization that may be more efficient than my current implementation. But I’ll need to try it out first :)
2 archived reader comments
Kristof Strobl (2004-09-22)
You could also use a list comprehension for the job. This powerful construct eliminates the use of both ‘map’ and ‘lambda’:
argIndices = (1, 2, 3, 4 , 5) # just for the code snippet to run groups = ‘,’.join(map(lambda str: ‘mo.group(%s)’ % str, argIndices)) print groups groups = ‘,’.join([‘mo.group(%s)’ % str for str in argIndices]) print groups
Daniel Dunbar (2004-09-22)
Also note that you could have used a list comprehension to kill some lines in the parser.__init__ function
self.templates = [templateExpression(regex, template) for regex,template in
inline_args]Although it is true they tend to “bulk” the code up somewhat, I still find them much more readable. I think it is because it clearly impresses the intent of the code (i.e. build up a list according to this rule) more clearly than appending does.