How to convert python tuple into a two-dimensional table?

PythonProgramming

If you have a numeric library like numpy available, you should use the reshape method to reshape the tuple to a multidimensional array. 

example

import numpy
data = numpy.array(range(1,10))
data.reshape([3,3])
print(data)

Output

This will give the output −

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

Example

If you prefer to do it in pure python, you can use a list comprehension −

data = tuple(range(1, 10))
table = tuple(data[n:n+3] for n in xrange(0,len(data),3))
print(table)

Output

This will give the output −

((1, 2, 3), (4, 5, 6), (7, 8, 9))
raja
Published on 18-Apr-2018 14:16:14
Advertisements