4

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),)      
2
  • is .tolist method enough? Commented Apr 10, 2018 at 15:36
  • See stackoverflow.com/q/49838872/901925 for newer similar question. Seems that poster wanted a structured array, not simply a list of tuples. Commented Apr 15, 2018 at 11:30

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

What about using tuble and map function like this:

import numpy
numpy_arr = numpy.array(((1527, 1369,   86,   86),(573 , 590 , 709,  709)))
converted_list = tuple(map(tuple,numpy_arr)) # as list
converted_arr = map(tuple,numpy_arr) #as array
print(converted_arr)

Comments

1

Here is the following function assuming you do not want the final object to be a numpy object.

def fun(var):
  a=[]
  for i in var:
    a.append(tuple(i))
  return a

if you want in one line

def fun(var):
  return [tuple(i) for i in var]

Comments

0

If you prefer list comprehensions to map():

a = numpy.random.uniform(0,1,size=(4,4))
a_tuple_list = [tuple(row) for row in a]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.