首页 > 解决方案 > 使用 python 将矩阵或列表()“写入”到 txt 文件

问题描述

我无法将矩阵输出写入我的文本文件:

results_stress = []
Element_list = []        
tau_list = []
press_list = []
vms_list = []
spmax_list = [] 
spmin_list = [] 
results_stress = [Element_list, tau_list, press_list, vms_list, spmax_list, spmin_list]
print ('results_stress', results_stress)

直到这里我的代码正在工作。它在屏幕上打印一个大列表。现在我想将它们写入我的文本文件。

wtrc ('%6.4f    %6.4f   %6.4f   %6.4f   %6.4f   %6.4f\n' %(Element_list, tau_list, press_list, vms_list, spmax_list, spmin_list))

请帮我以列格式写出上述所有 6 个列表。这样我就可以轻松地将其导入到 excel 文件中。

提前致谢

标签: pythonpython-3.xpython-requests

解决方案


给你一个例子:

Python 3.6.5 (default, Apr  1 2018, 05:46:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: num_fmt = '6.4f'

In [2]: results_stress = [[1.2, 10.2], [2.3, 20.3], [3.4, 30.4], [4.5, 40.5], [5.6, 50.6], [6.7, 60.7]]

In [3]: ss = []

In [4]: for nums in zip(*results_stress):
   ...:     ss.append((' '*4).join(f'{n:{num_fmt}}' for n in nums))
   ...:

In [5]: s = '\n'.join(ss)

In [6]: print(s)
1.2000    2.3000    3.4000    4.5000    5.6000    6.7000
10.2000    20.3000    30.4000    40.5000    50.6000    60.7000

推荐阅读