Monday, 5th March 2012
Converting a python list to an SVG path
Here's a short snippet of Python code that was I very pleased with. It converts a list of coordinates, such as this:
[(10, 200), (12, 220), (15, 180)]
Into the d attribute of an SVG path, such as this:
"M10 200 L12 220 L15 180"
I've written code for this several times, but it's always been quite inelegant because of the need for the first command to be 'M'. This is the first time I've coded it in one line, which is why I'm so pleased with myself. Here it is:
d = ' '.join(['%s%d %d' % (['M', 'L'][i>0], x, y) for i, (x, y) in enumerate(coord_list)])
It uses all my favourite tricks, including list comprehensions, Boolean indices, and enumerate, as well as string formatting and join. It's probably not as efficient because it needs to test i>0 for every coordinate, but I don't care.