0

I have encountered a problem in my code where I have to pass a 2D array to a function. The function works normally when I pass the values as [[166, 1692], [463, 1506], [113, 1572], [490, 1480]], but what I am receiving from another piece of code is this: [array([498]), array([1568])], [array([242]), array([1688])]]. I want to convert this format to the previous one. I want then in x,y format and I have tried many ways to convert back and forth and it does not work. I have to remove that "array" wrapper and also the "[]" wrapper around every element. Is there any way to do this? Any help will be much appreciated. Thank you.

UPDATE: Thank you for all the answers. The answer by Ayoub Zarou works as expected. Thank you once again.

2
  • can you show what you tried ? Commented Aug 1, 2019 at 13:04
  • 1
    According to the documentation you can use .tolist() to convert your array to a list. Commented Aug 1, 2019 at 13:05

4 Answers 4

3

I am assuming you are dealing with numpy arrays, "yourlist".tolist() should do the trick.

import numpy as np

a = np.array([[1, 2], [3, 4]])
a = list(a)
print(a)
# outputs [array([1, 2]), array([3, 4])]

print(np.array(a).tolist())
# outputs [[1, 2], [3, 4]]

# If you are removing the brackets, you can simply flatten() it.
a = np.array(a).flatten()
print(a.tolist())
# outputs [1, 2, 3, 4]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation and telling where I am going wrong.
0

try doing :

np.array(x).reshape((len(x), -1)).tolist()

where x is your list

1 Comment

Happy coding , you could approve the answer if it was helpful
0

Maybe this helps:

from numpy import array
a = [array([498]), array([1568]), array([242]), array([1688])]
b = array(a).tolist()
print(b)

Output is:

[[498], [1568], [242], [1688]]

Another solution which gives the same output:

import numpy as np
a = [array([498]), array([1568]), array([242]), array([1688])]
b = list(map(np.ndarray.tolist, a))

Comments

0

You can pick the first value out of each array with a list comprehension:

from numpy import array    
inlist = [[array([1]), array([2])], [array([3]), array([4])], [array([5]), array([6])]]
# form of inlist: [[array([1]), array([2])], [array([3]), array([4])], [array([5]), array([6])]]
outlist = [[a[0], b[0]] for a,b in inlist]

Which gives you

[[1, 2], [3, 4], [5, 6]]

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.