Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: converting tuple into 2D array

I want to convert tuple like

t = [(4,10),(9,7),(11,2),(2,2)]

into 2D array like:

a = [[4,10],[9,7],[11,2],[2,2]]

I tried

a = []
for i in t:  
    a.append(np.asarray(i))
print a

is there any easier way?

like image 433
eudaimonia Avatar asked Jan 17 '16 17:01

eudaimonia


People also ask

Is a tuple a 2D array?

Using a tuple to specify the size of the array in the first argument of the ones function creates a multidimensional array, in this case a two-dimensional array with the two elements of the tuple specifying the number of rows and columns, respectively.

Can tuple be multidimensional?

In Python a multidimensional tuple or list is one that contains another tuple or list as one of its elements. For example, take this tuple, which is composed of three separate tuples.

What is 2D tuple in Python?

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists which are mutable.

Is it possible to create an array from a tuple?

Yes, Any sequence that has an array-like structure can be passed to the np. array function.


1 Answers

Use a list comprehension as follows:

>>> t = [(4,10),(9,7),(11,2),(2,2)]
>>> [list(item) for item in t]
[[4, 10], [9, 7], [11, 2], [2, 2]]
like image 184
gtlambert Avatar answered Oct 14 '22 14:10

gtlambert