简体   繁体   English

将元组列表格式化为小数并将其添加到文件中

[英]Formatting list of tuples to decimals and adding them to a file

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. 在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. 为了获得这些坐标,我首先创建了一个空列表points = [] ,然后编写了一个函数来计算中心坐标,边数,边长和旋转角度的每个点。 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 x1,y1
x2, y2 x2,y2
... ...
xn, yn xn,yn

where each coordinate is written to 3 decimal places. 其中每个坐标写入3个小数位。 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. 因此,我需要将我的元组格式化为3位小数,然后将它们转换为字符串,然后将它们写入文件中,我希望它以最短的方式。

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 = [float("{:.3f}".format(j)) for j in points] (由于我有元组,因此不起作用)然后

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? 上面的解决方案对我来说似乎很好,但是我找不到为元组做第一行(格式化为小数)的方法,所以我想知道如何将元组列表格式化为小数以将它们存储在一个元组中下面使用writelines并转换成字符串的列表? Or if there is a shorter and better way of doing this, I would appreciate any hints. 或者,如果有更短更好的方法,我会感激任何提示。 Thank you! 谢谢!

You can directly write the floats into your file: 您可以直接将浮点数写入您的文件:

Testdata: 测试数据:

import random

tupledata = [(random.uniform(-5,5),random.uniform(-5,5) ) for _ in range(10)]
print(tupledata)

Output: 输出:

[(1.4248082335110652, 1.9169955985773148), (0.7948001195399392, 0.6827204752328884),
 (-0.7506234890561183, 3.5787165366514735), (-1.0180103847958843, 2.260945997153615), 
 (-2.951745273938622, 4.0178333333006435), (1.8200624561140613, -2.048841087823593), 
 (-2.2727453771856765, 1.3697390993773828), (1.3427726323007603, -1.7616141110472583), 
 (0.5022889371913024, 4.88736204694349), (2.345381610723872, -2.2849852099748915)]

Write to formatted: 写入格式化:

with open("n.txt","w") as w:
    # w.write(f"{len(tupledata)}\n")  # uncomment for line number on top
    for t in tupledata:                 
        w.write("{:.3f},{:.3f}\n".format(*t)) 

        # for python 3.6 up you can alternatively use string literal interpolation:
        # see    https://www.python.org/dev/peps/pep-0498/

        # w.write(f"{t[0]:.3f},{t[1]:.3f}\n")

with open("n.txt","r") as r:
    print(r.read())

Output in file: 文件输出:

1.425,1.917
0.795,0.683
-0.751,3.579
-1.018,2.261
-2.952,4.018
1.820,-2.049
-2.273,1.370
1.343,-1.762
0.502,4.887
2.345,-2.285

See proper name for python * operator? 查看python * operator的正确名称? for what *t does. 为了什么*t Hint: print(*[1,2,3]) == print(1,2,3) 提示: print(*[1,2,3]) == print(1,2,3)


You are mixing several things. 你混合了几件事。 There is no need to add the number in the list,nor you need to create an intermediary string list.Also the formatting is easier like this: 无需在列表中添加数字,也无需创建中间字符串列表。此格式化也更容易:

with open('points.txt', 'w') as f:
    f.write(str(len(points)))
    for x, y in points:
        f.write(f"{x:.2f}, {y:.2f}\n")

Use tuple unpacking when constructing your lines: 在构造线条时使用元组解包:

lines = ["{:.3f}, {:.3f}\n".format(*point) for point in points]

That way you already have a list of strings you can easily write to a file. 这样您就可以轻松地将文件列表写入文件。 No need to convert them to float again, just to cast them to string again. 无需再将它们转换为浮动,只需将它们再次转换为字符串即可。

with open('points.txt', 'w') as f:
    f.writelines(lines)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM