18

Here's the numpy.ndarray I've got:

a=[[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]]

and I want it to convert to

a = [(0.01, 0.02), (0.03, 0.04)]

Currently I just use the following for loop but I'm not sure whether it's efficient enough:

b = []
for point in a:
   b.append((point[0][0], point[0][1]))
print(b)

I've found somewhat a similar question but there're no tuples so a suggested ravel().tolist() approach didn't work for me here.

3
  • Why are you using a lsit? Commented Mar 25, 2019 at 11:35
  • PS. you cannot append 2 elements in a list Commented Mar 25, 2019 at 11:35
  • @DirtyBit I'm sorry, just edited the question. Commented Mar 25, 2019 at 11:41

2 Answers 2

22
# initial declaration
>>> a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
>>> a
array([[[0.01, 0.02]],
       [[0.03, 0.04]]])

# check the shape
>>> a.shape
(2L, 1L, 2L)

# use resize() to change the shape (remove the 1L middle layer)
>>> a.resize((2, 2))
>>> a
array([[0.01, 0.02],
       [0.03, 0.04]])

# faster than a list comprehension (for large arrays)
# because numpy's backend is written in C

# if you need a vanilla Python list of tuples:
>>> list(map(tuple, a))
[(0.01, 0.02), (0.03, 0.04)]

# alternative one-liner:
>>> list(map(tuple, a.reshape((2, 2))))
...
Sign up to request clarification or add additional context in comments.

2 Comments

Any reason you put the 2L there? In Python 3 all integers are long integers, so I would propose to remove those Ls as to not confuse new Python programmers into thinking this is "good style" or even "required".
@NOhs I did so for consistency but I see your point, will edit thanks.
4

You can use list comprehension, they are faster than for loops

a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
print([(i[0][0], i[0][1]) for i in a])  # [(0.01, 0.02), (0.03, 0.04)]

alternatively:

print([tuple(l[0]) for l in a])  # [(0.01, 0.02), (0.03, 0.04)]

3 Comments

Not bad either! ;)
Shorter alternative: tuple(i[0]).
@DirtyBit you shouldn't alter his solution without his consent, because there was nothing wrong with it. My comment was just for future reference.

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.