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

时间:2018-11-15 07:32:41

标签: python python-3.x tuples string-formatting

我有一个元组列表作为坐标(必须是这种方式)

HibernateTemplate template = getHibernateTemplate();
    DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.max("productCount"));
    projectionList.add(Projections.avg("productCount"));
    projectionList.add(Projections.sum("productCount"));

    criteria.add(Restrictions.gt("productCount", 5));
    criteria.setProjection(projectionList);

    List<?> list = template.findByCriteria(criteria);
    System.out.println(list.get(0));
    System.out.println(list.get(1));
    System.out.println(list.get(2));

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

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

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

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

我以为我会做类似points = []的事情(由于我有元组,所以不起作用),然后

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) 使用和转换为字符串? 或者,如果有更短更好的方法,我将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:5)

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

测试数据:

import random

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

输出:

[(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)]

写入格式:

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())

文件输出:

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

有关*t的用途,请参见proper name for python * operator?。提示:print(*[1,2,3]) == print(1,2,3)


答案 1 :(得分:2)

您正在混合几件事。无需在列表中添加数字,也无需创建中间字符串列表。这样的格式设置更容易:

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")

答案 2 :(得分:1)

构造线时使用元组拆包:

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

这样,您已经有了一个字符串列表,可以轻松地将其写入文件。无需将它们转换为再次浮动,只需将它们再次转换为字符串即可。

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