可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
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:
Line 1:1 2 3 4 5 6 7
Line 2:8 9 10 11 12 13 14
回答1:
you could do this:
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
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
hope that helps!
回答2:
Your question can be broken down into 3 parts:
- How to divide a list of arbitrary size into chunks of a specific length
- How to print a list of ints/floats using a space as delimiter
- How to write to a file
Dividing a list of arbitrary size into chunks of a specific length
Using the grouper
method as described in 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
you can easily split a list of arbitrary length to chunks of a desired length. For example:
>>> 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)
Printing a list of ints/floats using a space as delimiter
The standard way to join a list into a string is to use string.join()
. However, that only works for lists of strings so we'll need to first convert each element into its string representation. Here's one way:
>>> a = [1, 2, 3, 4]
>>> print " ".join(str(x) for x in a)
1 2 3 4
Using this method in the previous example, we get:
>>> 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
That's pretty much the output you want. Now all we need to do is write that to a file.
Writing to a file
with open("outfile.txt", "w") as f:
for chunk in grouper(7, arr1):
f.write(" ".join(str(x) for x in chunk) + "\n")
For details, see Reading and Writing Files.
回答3:
>>> [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]]
Then you just have to iterate in this list (of lists), to insert them in the file.
回答4:
>>> 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]
or you could do:
>>> 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'
回答5:
You can chunk a sequence using this zip
idiom:
from itertools import izip
def chunk(seq, n):
return izip(*[iter(seq)]*n)
You can then compose an iterator for writelines
:
def chunkedlines(seq, n):
for line in chunk(seq, 7):
yield ' '.join(str(item) for item in line)
yield "\n"
Finally use it:
from StringIO import StringIO
fp = StringIO('wb')
arr1 = range(1, 15)
fp.writelines(chunkedlines(arr1, 7))
print fp.getvalue()
回答6:
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
回答7:
In Python, think "generator" !
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)
result
1 2 3 4 5 6 7
8 9 10 11 12 13 14
101 203 514 201 567 849
And if you want to parameterize the number of numbers in each line, create a generator function:
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))
回答8:
from itertools import imap
print '\n'.join((' '.join(imap(str, arr1[i*7:(i+1)*7])) for i in xrange((6+len(arr1))/7)))
Or,
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)
Combining the nested join
s with the izip
technique:
print '\n'.join((' '.join(j) for j in izip(*[imap(str, arr1)]*7)))