如何每行将多个数组元素打印到文本文件 [英] How to print several array elements per line to text file

查看:97
本文介绍了如何每行将多个数组元素打印到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个一维数组,例如arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...]任意长度.

I have a 1D array e.g. arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...] of arbitrary length.

如何将其打印到文本文件中(整数/浮点数用空格分隔),以便每7个元素打印在文本文件的同一行上?

How do I print this to a text file (with integers/floats separated by spaces) so that every 7 elements are printed on the same line in the text file?

所以我希望文本文件看起来像这样:

So I want the text file to look like this:

第1行:1 2 3 4 5 6 7

第2行:8 9 10 11 12 13 14

推荐答案

您可以执行以下操作:

liNums = xrange(1, 20)
x = 0
line = ""
for i in liNums:
    x+=1
    line += "%s " % i
    if not x%7:
        line += "\n"
#send line to output, here I will just print it
print line

每7个项目都会附加一个新行...输出看起来像这样:

here every 7 items a new line is appended... output looks like this:

1 2 3 4 5 6 7 
8 9 10 11 12 13 14 
15 16 17 18 19 

希望有帮助!

这篇关于如何每行将多个数组元素打印到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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