Skip to content Skip to sidebar Skip to footer

Write To List To Rows With Specific Number Of Columns

I'm trying to write a list to rows with a specific number of columns. For example, take the list: data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0] I would like to write

Solution 1:

defchunks(seq, n):
    # http://stackoverflow.com/a/312464/190597 (Ned Batchelder)""" Yield successive n-sized chunks from seq."""for i in xrange(0, len(seq), n):
        yield seq[i:i + n]

data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
for row in chunks(data, 3):
    print(',  '.join(map(str, row)))

yields

1.0,  2.0,  3.0
4.0,  5.0,  6.0
7.0,  8.0,  9.0
10.0

Or, perhaps closer to your code:

strformat ='\n'.join(
    ',  '.join('{:>5.1f}'for item inrow) 
    forrowin chunks(data, 3))
print(strformat.format(*data))

Solution 2:

So, you're actually trying to do two things here.

First, you're trying to columnize your list (transform it to a new structure that has three elements in each item). You can write a function that looks a bit like this:

defcolumnize(data, columns):
    for i in xrange(0, len(data), columns):
        yield data[i:i+columns]

Then you're looking to print them with a specified format. What you have is workable, but you can make it a little simpler by skipping the positional arguments. Instead of '{0} {1} {2}', you can actually just supply '{} {} {}' because the arguments are formatted in order. The printing code would look like:

columns = 3for row in columnize(data, columns):
    strformat = '{:>5.1f},' * len(row)
    print strformat.format(*row)

Note that we can handle the case of the last row just by using the string multiplication operator; most times, row will have 3 items, but on the last one it has just one.

Solution 3:

Well, this is a fairly simple way; splitting the list at regular intervals. It also prints with right alignment, depending on the length of the longest item in the list. Not very terribly concise, but it seems to me like what you're after.

data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
width = 3

table = [data[x:x+width] for x inrange(0, len(data), width)]
alignment = len(str(max(data)))

for i in table:
    for j in i:
        print"%s," % str(j).rjust(alignment),
    print

 1.0,  2.0,  3.0,
 4.0,  5.0,  6.0,
 7.0,  8.0,  9.0,
10.0,

And with longer items:

1.0,2.0,3.0,400.0,5000.0,6.0,7.0,8.0,9.0,10.0,

Solution 4:

I love Joseph's solution, maybe just...

print "%s," % str(j).rjust(alignment, ' '),

Post a Comment for "Write To List To Rows With Specific Number Of Columns"