2

I'm trying to get rid of some characters in my array so I'm just left with the x and y coordinates, separated by a comma as follows:

[[316705.77017187304,790526.7469308273]
 [321731.20991025254,790958.3493565321]]

I have used zip() to create a tuple of the x and y values (as pairs from a list of strings), which I've then converted to an array using numpy. The array currently looks like this:

[['316705.77017187304,' '790526.7469308273,']
 ['321731.20991025254,' '790958.3493565321,']]

I need the output to be an array.

I'm pretty stumped about how to get rid of the single quotes and the second comma. I have read that map() can change string to numeric but I can't get it to work.

Thanks in advance

4
  • Is your required output is first one? Commented Jan 25, 2014 at 15:00
  • Yes it is. Just had a thought, do I need to convert the strings to numbers before adding them to the tuple? Thanks Commented Jan 25, 2014 at 15:02
  • I am not very sure check my answer below.. may be helpful for you else I will delete. Commented Jan 25, 2014 at 15:11
  • I have read that map() can change string to numeric not actually... Commented Jan 25, 2014 at 15:22

1 Answer 1

1

Using 31.2. ast — Abstract Syntax Trees¶

import ast
xll =  [['321731.20991025254,' '790958.3493565321,'], ['321731.20991025254,' '790958.3493565321,']]
>>> [ast.literal_eval(xl[0]) for xl in xll]
[(321731.20991025254, 790958.3493565321), (321731.20991025254, 790958.3493565321)]

Above gives list of tuples for list of list, type following:

>>> [list(ast.literal_eval(xl[0])) for xl in xll]
[[321731.20991025254, 790958.3493565321], [321731.20991025254, 790958.3493565321]]

OLD: I think this:

>>> sll
[['316705.770172', '790526.746931'], ['321731.20991', '790958.349357']]
>>> fll = [[float(i) for i in l] for l in sll]
>>> fll
[[316705.770172, 790526.746931], [321731.20991, 790958.349357]]
>>> 

old Edit:

>>> xll =  [['321731.20991025254,' '790958.3493565321,'], ['321731.20991025254,' '790958.3493565321,']]
>>> [[float(s) for s in xl[0].split(',') if s.strip() != ''] for xl in xll]
[[321731.20991025254, 790958.3493565321], [321731.20991025254, 790958.3493565321]]
Sign up to request clarification or add additional context in comments.

2 Comments

Once I removed the commas from the original strings, your "OLD" answer seems to have done the trick. Brilliant, thank you!
@user2727152 Try: [[float(s) for s in xl[0].split(',') if s.strip() != ''] for xl in xll] to remove , and convert into float in one step.

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.