Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a list with specified column width in Python?

Tags:

python

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?

like image 714
JasonChiuCC Avatar asked Aug 02 '26 06:08

JasonChiuCC


1 Answers

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.

like image 110
timgeb Avatar answered Aug 03 '26 19:08

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!