如何在Python中编写要列出的列表的浮动列表 [英] How do I write a float list of lists to file in Python

查看:56
本文介绍了如何在Python中编写要列出的列表的浮动列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一系列矩阵写到python的纯文本文件中.我所有的矩阵都是浮点格式,所以简单 file.write()和file.writelines()

I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()

不起作用.有没有一种我可以采用的转换方法,而不必让我遍历所有列表(在我的情况下为矩阵=列表列表)来转换各个值?

do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the individual values?

我想我应该澄清一下,它不必看起来像矩阵,而只是一个易于解析的列表中的关联值,正如我稍后将要读到的那样.实际上,将所有内容全部放在一行中可以使它更容易!

I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!

推荐答案

m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]
file.write(str(m))

如果您想进一步控制每个值的格式:

If you want more control over the format of each value:

def format(value):
    return "%.3f" % value

formatted = [[format(v) for v in r] for r in m]
file.write(str(formatted))

这篇关于如何在Python中编写要列出的列表的浮动列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆