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.