在python3中使用数组将变量写入txt文件

2024-09-30 08:18:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从csv数据集中计算各种数字(平均值、中位数等),然后将这些信息写入txt文件。作为参考,我的数据集是SAT分数,所以下面的示例是SAT阅读分数代码。现在我正在尝试使用一个数组,并且有:

    a=[1,2,3,4,5,6]
    b=[rmean, rmed, rmax, rmin, rsd, rvar]

    output=open("output.txt", "w")
    output.write("For the variable READ:\n The mean is")
    for i in range(len(a)):
        output.write(" %i %5.2f\n" % (a[i], b[i]))
    output.close()


我希望我的txt文件看起来像:

For the variable READ, the mean is [value of rmean variable], the median is [value of rmed variable], etc.

如何操纵数组来实现这一点,而不是它当前输出的矩阵视图?另外,有没有办法避免使用数组a中的数字,或者避免它们出现在我的txt文件输出中?谢谢您!你知道吗


Tags: 文件the数据txtforoutputis数字
2条回答

我是否正确理解您只想打印一行所有值,并且所有值都已计算并保存为变量? 在这种情况下,不需要for循环

output.write("For the variable READ:\n The mean is {0}, the median is {1}, the max is {2}, etc".format(rmean, rmedian, rmax, ...))

当然,如果你想从你的名单上读

output.write("For the variable READ:\n The mean is {0}, the median is {1}, the max is {2}, etc".format(b[0], b[1], b[2], ...))

我的解决方案是:

with open("output.txt", "w") as f:
    f.write("For the variable READ:\n ")
    for i in range(len(a)):
        f.write("The %4s is %5.2f\n" %(b[i][1:], a[i]))

但如果你把你的b改成:

b = ['mean', 'median', 'max', 'min', 'sd', 'variance']


with open("output.txt", "w") as f:
    f.write("For the variable READ:\n ")
    for i in range(len(a)):
        f.write("The %-8s is %5.2f\n" %(b[i], a[i]))

相关问题 更多 >

    热门问题