0

I'm reading in a list of coordinates from a kml file giving me this output:

['-73.9972973,40.7075148', ..., '-73.9850235,40.7900946']

(Imagine the ... as a lot more coordinates similar to the first and last) I'm using the following code to try to accomplish this but it won't work.

manhattanCoords = []

for coord in coords:
    pair = [float(s) for s in coord.strip().split(", ")]
    manhattanCoords.append(pair)

I get the following error:

Traceback (most recent call last):
  File "Manhattan_Coords_Extract.py", line 12, in <module>
    pair = [float(s) for s in coord.strip().split(", ")]
  File "Manhattan_Coords_Extract.py", line 12, in <listcomp>
    pair = [float(s) for s in coord.strip().split(", ")]
ValueError: could not convert string to float: '-73.9972973,40.7075148'

Does anyone have any suggestions?

jqwerty
  • 37
  • 1
  • 6

2 Answers2

3

You can iterate through your list, and .split() on ',' characters. Then you can convert them to float. In a list comprehension, that would be the following.

l = ['-123.456,532.643', '245.234,241.678', '345.342,344.342']
coords = [map(float,i.split(',')) for i in l]

>>> coords
[[-123.456, 532.643], [245.234, 241.678], [345.342, 344.342]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • This only returns a list of map objects for me? – jqwerty Sep 12 '14 at 23:40
  • No. `map` is a function that means "perform this operation on each member of the list", so I am using it to convert the split `string` values to `float`. So the returned list `coords` is a `list` of `list` of `float`. – Cory Kramer Sep 12 '14 at 23:41
0

Use .split(",") not .split(", ")

(no space)

Thanks to Zero Piraeus for the answer!

jqwerty
  • 37
  • 1
  • 6