4

I have list of tuples (x,y coordinates) converted to a string and written in a file. When I read line from file, my list looks like this:

[(341, 115), (174, 227), (457, 308)]

how do I convert this kind of list to numpy array? end result should look like this:

[[341 115]
 [174 227]
 [457 308]]
2
  • np.array("[(341, 115), (174, 227), (457, 308)]") ? Commented Mar 12, 2019 at 12:49
  • 1
    np.array(literal_eval("[(341, 115), (174, 227), (457, 308)]")) ? Commented Mar 12, 2019 at 12:56

2 Answers 2

3

Using numpy:

lst = [(341, 115), (174, 227), (457, 308)]

import numpy as np
print(np.array(lst))

OUTPUT:

[[341 115]
 [174 227]
 [457 308]]

Using list comprehension:

print([list(lst) for lst in lst])

OUTPUT:

[[341, 115], [174, 227], [457, 308]]

EDIT:

If it is a string which it does not look like in the code pasted in the question:

lst = "[(341, 115), (174, 227), (457, 308)]"

Then:

import numpy as np
from ast import literal_eval
print(np.array(literal_eval(lst)))

Eventually (for list comprehension):

print([list(lst) for lst in literal_eval(lst)])
Sign up to request clarification or add additional context in comments.

1 Comment

[int(x) for x in lst] is redundant as all elements in lst are already of type int. Just use list(lst).
1

Use ast.literal_eval to convert the line (a string) to an actual list object, and call numpy.array directly on it:

line = "[(341, 115), (174, 227), (457, 308)]"

from ast import literal_eval
import numpy as np

np.array(literal_eval(line))

Output:

array([[341, 115],
   [174, 227],
   [457, 308]])

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.