简体   繁体   English

如何在Python中编写列表的浮动列表

[英]How do I write a float list of lists to file in Python

I need to write a series of matrices out to a plain text file from python. 我需要从python中写一系列矩阵到纯文本文件。 All my matricies are in float format so the simple file.write() and file.writelines() 我的所有matricies都是浮点格式,所以简单的file.write()和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))

the following works for me: 以下为我工作:

with open(fname, 'w') as f:
    f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix)

Why not use pickle ? 为什么不用泡菜

import cPickle as pickle
pckl_file = file("test.pckl", "w")
pickle.dump([1,2,3], pckl_file)
pckl_file.close()
import pickle

# write object to file
a = ['hello', 'world']
pickle.dump(a, open('delme.txt', 'wb'))

# read object from file
b = pickle.load(open('delme.txt', 'rb'))
print b        # ['hello', 'world']

At this point you can look at the file 'delme.txt' with vi 此时,您可以使用vi查看文件'delme.txt'

vi delme.txt
  1 (lp0
  2 S'hello'
  3 p1
  4 aS'world'
  5 p2
  6 a.

for row in matrix: file.write(" ".join(map(str,row))+"\\n") 对于矩阵中的行:file.write(“”。join(map(str,row))+“\\ n”)

This works for me... and writes the output in matrix format 这对我有用......并以矩阵格式写出输出

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

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