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.

Topics:

Comments

ah. very neat. this will come in handy.

d = ' '.join([ '{0}{1[0]} {1[1]}'.format(*x) for x in zip('MLL', coord_list) ])

The code in the comment above will only work if there are three coordinates, but I want something that will work for an abitrary number of coordinates.

Post new comment

The content of this field is kept private and will not be shown publicly.