2

I have a list like

mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

How can I print the list with a specified column width

For example, I want to print column = 5 then new line

print(mylist, column= 5)
[ 1,  2,  3,  4,  5, 
  6,  7,  8,  9, 10, 
 11, 12, 13, 14, 15, 
 16, 17, 18, 19, 20]

Or I want to print column = 10 then new line

print(mylist, column= 10)
[ 1,  2,  3,  4,  5, 6,  7,  8,  9, 10, 
 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

I know I can use for-loop to do that, but I want to know is there is a function to do so already?

Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
JasonChiuCC
  • 111
  • 1
  • 6

3 Answers3

5

Use a numpy array instead of a list and reshape your array.

>>> import numpy as np
>>> array = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
>>>
>>> column = 5
>>> print(array.reshape(len(array)/column, column))
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
>>>>>> column = 10
>>> print(array.reshape(len(array)/column, column))
[[ 1  2  3  4  5  6  7  8  9 10]
 [11 12 13 14 15 16 17 18 19 20]]

Of course, this will throw a ValueError if it is not possible to divide array into column equally sized columns.

timgeb
  • 76,762
  • 20
  • 123
  • 145
4

not sure why but i think something close to what i think you want to achieve can be done using numpy array reshape by fixing the number of rows to -1

import numpy as np
array=np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]) array
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20])
array.reshape(-1,5)

gives

array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20]])

array.reshape(-1,10)

gives

array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]])
Eliethesaiyan
  • 2,327
  • 1
  • 22
  • 35
  • 1
    Cool, I did not know that `reshape` accepts -1 as an argument. More info here: https://stackoverflow.com/questions/18691084/what-does-1-mean-in-numpy-reshape – timgeb May 30 '17 at 08:20
1

You can do this by using slicing also.

mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

def print_list(mylist, no_of_cols):
    start_index = 0
    for i in range(no_of_cols, len(mylist), no_of_cols):
        print mylist[start_index:i]
        start_index = i

    if len(mylist) > start_index:
        print mylist[start_index:len(mylist)]

print_list(mylist, 5)
SuperNova
  • 25,512
  • 7
  • 93
  • 64