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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With