简体   繁体   中英

Printing multiple items in list in different lines

I need help in a project where i have a board which is in a list of 25 items. How can I print so that it skips line every 5 items. If I have this:

    myList = []
    for i in range (1,25):
        myList.append(i)

I've looked at '\\n' and print(myList, end='') but I haven't gotten anywhere. I want an end result like this:

    1  2  3  4  5
    6  7  8  9  10
    11 12 13 14 15
    16 17 18 19 20
    21 22 23 24 25

Thank you very much.

To have a list which goes from 1 to 25 you need to do range(1, 26) . Apart from that, you can print it in the format you asked just by doing:

numbers = range(1, 26)
for i, elem in enumerate(numbers):
    if i % 5 == 0:
        print()
    print(str(elem).ljust(3), end='')
print()

Output:

1  2  3  4  5  
6  7  8  9  10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25

enumerate(list) returns a pair (index, element) for every element in the list. str.ljust(n) left-justifies the string so that it is n characters long, padding the rest with spaces.

EDIT: alternatively, as proposed by @PM_2Ring in the comments:

numbers = range(1, 26)
for i, elem in enumerate(numbers, 1):
    print(str(elem).ljust(3), end='\n' if i % 5 == 0 else '')

As an alternative to str(elem).ljust(3) you can also use '{:<3}'.format(elem) (Python 2.7+) or '{0:<3}'.format(elem) (Python <2.7)

for i in range(len(myList)/5+1):
    print " ".join([str(j) for j in myList[5*i:5*i+5]])

You could work with arrays since you can easily reshape them into your board size:

import numpy as np
array = np.arange(1,26)
array = array.reshape((5,5))

for line in range(0,5):
    print ' '.join(map(str, array[line,:]))

Just for fun, here's an inscrutable functional one-liner:

print('\n'.join(map(''.join, zip(*[iter(map('{0:>3}'.format, myList))] * 5))))

Note that while this may look cool (to some readers), such dense nested code is really not recommended for use in real programs.

Here's essentially the same algorithm split up to make it more readable, with one of the map call converted to a list comprehension:

strings = map('{0:>3}'.format, myList)
chunked = zip(*[iter(strings)] * 5)
rows = [''.join(s) for s in chunked]
print '\n'.join(rows)

The trickiest part of this algorithm is the zip(*[iter(strings)] * 5) . The [iter(strings)] * 5 part creates a list of 5 references to an iterator over the strings iterable. The * splat operator passes those references to zip as separate arguments. zip then creates tuples of length 5 drawing from each of its arguments in turn to fill the tuples. But each of its arguments is a reference to the same iterator, iter(strings) , thus the contents of that iterator get packaged up into tuples.

Loop over every fifth element and add the in-between numbers:

for y in range(1, 26, 5):
    print "\t{0}\t{1}\t{2}\t{3}\t{4}".format(y, y+1, y+2, y+3, y+4)

For more items per line a double loop is easier:

for y in range(1, 26, 5):
    for x in range(y, y+5):
        out += "\t" + str(x)
    out += "\n"
print out

I used the tab character here, but you can also use the ljust function of string.

Using some map:

myList = range(1, 26)
for line in map(lambda x: myList[x:x+5], range(0, len(myList), 5)):
    print '\t'.join(map(str, line))

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
from math import sqrt

r = range(25)
n =int(sqrt(len(r)))

for i in xrange(0,n):
    print "\t".join([str(s) for s in r[i*n:i*n+n]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM