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

spf*_*ray 4 python tuples string-formatting python-3.x

我有一个元组列表作为坐标(必须这样)

points = [(x1, y1), (x2, y2), ...]
Run Code Online (Sandbox Code Playgroud)

在matplotlib中绘制一个多边形.为了获得这些坐标,我首先创建了一个空列表points = [],然后编写了一个函数来计算中心坐标,边数,边长和旋转角度的每个点.在函数之后,我编写了一个代码,用于从用户输入中读取上述初始值并检查其有效性,然后在检查成功时调用该函数.

现在我想将坐标和点数存储在文件中,如下所示:

点数
x1,y1
x2,y2
...
xn,yn

其中每个坐标写入3个小数位.因此,我需要将我的元组格式化为3位小数,然后将它们转换为字符串,然后将它们写入文件中,我希望它以最短的方式.

我以为我会做类似的事情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)
Run Code Online (Sandbox Code Playgroud)

上面的解决方案对我来说似乎很好,但是我找不到为元组做第一行(格式化为小数)的方法,所以我想知道如何将元组列表格式化为小数以将它们存储在一个元组中列表用于以下使用writelines和转换为字符串?或者,如果有更短更好的方法,我会感激任何提示.谢谢!

Pat*_*ner 5

您可以直接将浮点数写入您的文件:

测试数据:

import random

tupledata = [(random.uniform(-5,5),random.uniform(-5,5) ) for _ in range(10)]
print(tupledata)
Run Code Online (Sandbox Code Playgroud)

输出:

[(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)]
Run Code Online (Sandbox Code Playgroud)

写入格式化:

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())
Run Code Online (Sandbox Code Playgroud)

文件输出:

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
Run Code Online (Sandbox Code Playgroud)

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