I have a list of tuples as coordinates (it has to be this way)
points = [(x1, y1), (x2, y2), ...]
to draw a polygon in matplotlib. To get these coordinates I first created an empty list points = []
and then wrote a function to calculate each point from the coordinates of the centre, number of sides, side length and angle of rotation. After the function I wrote a code to read the above initial values from user's input and check their validity, and then call the function if the check is successful.
Now I want to store the coordinates and the number of points in a file as follows:
number of points
x1, y1
x2, y2
...
xn, yn
where each coordinate is written to 3 decimal places. Therefore, I need to format my tuples to 3 decimals, then convert them to strings and then write them in a file, and I want it in the shortest possible way.
I thought I would do something like lines = [float("{:.3f}".format(j)) for j in points]
(which doesn't work since I have tuples) and then
lines.insert(0, len(points))
with open('points.txt', 'w') as f:
f.writelines("%s\n" % l for l in lines)
The above solution seems very nice to me, but I can't find a way to do the first line (formatting to decimals) for tuples, so I was wondering how could I possibly format a list of tuples to decimals to store them in a list for the following use of writelines
and conversion into strings?
Or if there is a shorter and better way of doing this, I would appreciate any hints. Thank you!