Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert numpy array into tuple

I need to convert array like this:

 [[1527 1369   86   86]
  [ 573  590  709  709]
  [1417 1000   68   68]
  [1361 1194   86   86]]

to like this:

    [(726, 1219, 1281, 664),
    (1208, 1440, 1283, 1365), 
    (1006, 1483, 1069, 1421),
    (999, 1414, 1062, 1351),]

I tried using convert diretly to tuple but got this:

         ( array([1527, 1369,   86,   86], dtype=int32), 
           array([573, 590, 709, 709], dtype=int32),
           array([1417, 1000,   68,   68], dtype=int32), 
           array([1361, 1194,   86,   86], dtype=int32))
           (array([701, 899, 671, 671], dtype=int32),)      
like image 754
Karan Purohit Avatar asked Oct 27 '25 19:10

Karan Purohit


1 Answers

The array method tolist is a easy and fast way of converting an array to a list. It handles multiple dimensions correctly:

In [92]: arr = np.arange(12).reshape(3,4)
In [93]: arr
Out[93]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
In [94]: arr.tolist()
Out[94]: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

For most purposes such as list of lists is just as good as a list of tuples, or tuple of tuples. They differ only in mutability.

But if you must have a tuples, a list comprehension does the conversion nicely.

In [95]: [tuple(x) for x in arr.tolist()]
Out[95]: [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]

An alternative [tuple(x) for x in arr] is a bit slower, because it is iterating on the array rather than on a list. It also produces a different result - though you have to examine the type of the tuple elements to see that.

I strongly recommend starting with the tolist method, and doing any list to tuple conversions after.

like image 71
hpaulj Avatar answered Oct 30 '25 08:10

hpaulj



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!