[英]How do I write a float list of lists to file in Python
我需要從python中寫一系列矩陣到純文本文件。 我的所有matricies都是浮點格式,所以簡單的file.write()和file.writelines()
不工作。 有沒有我可以使用的轉換方法,我沒有循環遍歷所有列表(矩陣=我的情況下的列表列表)轉換單個值?
我想我應該澄清一下,它不需要看起來像一個矩陣,只需要一個易於解析的列表中的相關值,我將在稍后閱讀。 所有在一條線上實際上可以使這更容易!
m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]
file.write(str(m))
如果您想要更多地控制每個值的格式:
def format(value):
return "%.3f" % value
formatted = [[format(v) for v in r] for r in m]
file.write(str(formatted))
以下為我工作:
with open(fname, 'w') as f:
f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix)
為什么不用泡菜 ?
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']
此時,您可以使用vi查看文件'delme.txt'
vi delme.txt
1 (lp0
2 S'hello'
3 p1
4 aS'world'
5 p2
6 a.
對於矩陣中的行:file.write(“”。join(map(str,row))+“\\ n”)
這對我有用......並以矩陣格式寫出輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.