我有一个一维数组,例如arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ...]
任意长度。
如何将其打印到文本文件(整数/浮点数用空格分隔,以便每7个元素打印在文本文件的同一行上?
所以我希望文本文件看起来像这样:
第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个项目都会添加一个新行...输出看起来像这样:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19
希望有帮助!
您的问题可以分为三部分:
使用grouper
中所述的this answer方法:
import itertools
def grouper(n, iterable):
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, n))
if not chunk:
return
yield chunk
您可以轻松地将任意长度的列表拆分为所需长度的块。例如:
>>> arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> for chunk in grouper(7, arr1): print chunk
...
(1, 2, 3, 4, 5, 6, 7)
(8, 9, 10, 11, 12, 13, 14)
(15, 16)
将列表连接到字符串的标准方法是使用string.join()
。但是,这仅适用于字符串列表,因此我们需要首先将每个元素转换为其字符串表示形式。这是一种方法:
string.join()
在上一个示例中使用此方法,我们得到:
>>> a = [1, 2, 3, 4]
>>> print " ".join(str(x) for x in a)
1 2 3 4
几乎就是您想要的输出。现在,我们要做的就是将其写入文件。
>>> for chunk in grouper(7, arr1):
... print " ".join(str(x) for x in chunk)
...
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16
有关详细信息,请参见with open("outfile.txt", "w") as f:
for chunk in grouper(7, arr1):
f.write(" ".join(str(x) for x in chunk) + "\n")
。
Reading and Writing Files
然后,您只需要在此列表中进行迭代,即可将它们插入文件中。
>>> [arr1[7 * i: 7 * i + 7] for i in range(0, 1 + len(arr1) / 7)]
[[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15]]
或者您可以这样做:
>>> arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> for i in xrange(0,len(arr1),7):
... print arr1[i:i+7]
...
[1, 2, 3, 4, 5, 6, 7]
[8, 9, 10, 11, 12, 13, 14]
您可以使用此>>> arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> results = map(str,arr1)
>>> for i in range(0,len(arr1),7):
... ','.join(results[i:i+7])
...
'1,2,3,4,5,6,7'
'8,9,10,11,12,13,14'
习惯用法对序列进行分块:
zip
然后您可以为from itertools import izip
def chunk(seq, n):
return izip(*[iter(seq)]*n)
组成一个迭代器:
writelines
最终使用它:
def chunkedlines(seq, n):
for line in chunk(seq, 7):
yield ' '.join(str(item) for item in line)
yield "\n"
from StringIO import StringIO
fp = StringIO('wb')
arr1 = range(1, 15)
fp.writelines(chunkedlines(arr1, 7))
print fp.getvalue()
在Python中,请考虑“生成器”!
output=''
col = 0
for i in arr1:
output +="%s " % i #write an element of the array to the output and append a space
col += 1 #count the number of elements on the current line
if col==7: #if 7 elements have been entered, append a new line and restart the count
output += "\n"
col = 0
f = open("filepath.txt",'w') #open a file (replace filepath.txt with the actual filename)
f.write(output) # write the output to the text file
f.close() #close the file object
结果
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,101,
203,514,201,567,849]
gen = ('%-5s\n' % x if i%7==0 else '%-5s' %x
for i,x in enumerate(li,1))
print ''.join(gen)
如果要参数化每行中数字的数量,请创建一个生成器函数:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
101 203 514 201 567 849
def yn(li,n):
for i,x in enumerate(li,1):
yield '%-5s ' % x
if i%n==0:
yield '\n'
print ''.join(yn(li,7))
或,
from itertools import imap
print '\n'.join((' '.join(imap(str, arr1[i*7:(i+1)*7])) for i in xrange((6+len(arr1))/7)))
将嵌套的 groups_of_seven = (arr1[i*7:(i+1)*7] for i in xrange((6+len(arr1))/7))
groups_of_seven_strings = (imap(str, i) for i in groups_of_seven)
groups_of_strings = (' '.join(i) for i in groups_of_seven_strings)
one_string = '\n'.join(groups_of_strings)
与join
技术结合:
izip