How to print several array elements per line to te

2020-03-07 06:43发布

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

8条回答
Anthone
2楼-- · 2020-03-07 06:46

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))
查看更多
等我变得足够好
3楼-- · 2020-03-07 06:53

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()
查看更多
淡お忘
4楼-- · 2020-03-07 06:56

Your question can be broken down into 3 parts:

  1. How to divide a list of arbitrary size into chunks of a specific length
  2. How to print a list of ints/floats using a space as delimiter
  3. 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.

查看更多
爷、活的狠高调
5楼-- · 2020-03-07 07:02
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
查看更多
在下西门庆
6楼-- · 2020-03-07 07:04

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!

查看更多
一纸荒年 Trace。
7楼-- · 2020-03-07 07:09
>>> 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'
查看更多
登录 后发表回答