Home > Mobile >  coverting list of string coordinates into list of coordinates without string
coverting list of string coordinates into list of coordinates without string

Time:11-17

I have a list

flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8']

How can I convert it into

[[53295,-46564.2], [53522.6,-46528.4], [54792.9,-46184], [55258.7,-46512.9], [55429.4,-48356.9], [53714.5,-50762.8]]

I tried

l = [i.strip("'") for i in flat_list]

nothing works.

l = [i.strip("'") for i in flat_list]

coords = [map(float,i.split(",")) for i in flat_list]
print(coords) 

gives me <map object at 0x7f7a7715d2b0>

CodePudding user response:

Why complicate things?

Without any builtins such as map and itertools, this approach with a nested list comprehension should be a relatively simple and efficient one.

flat_list = ['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9',
             '53714.5,-50762.8']

result = [float(f) for pair in flat_list for f in pair.split(',')]

print(result)

Output:

[53295.0, -46564.2, 53522.6, -46528.4, 54792.9, -46184.0, 55258.7, -46512.9, 55429.4, -48356.9, 53714.5, -50762.8]

CodePudding user response:

Edit after your comment: to get a list of lists you can use

list2 = [[float(f) for f in el.split(",")] for el in flat_list]

or

list2 = [list(map(float,el.split(","))) for el in flat_list]

Deprecated: If you are okay with 2 operations instead of a one-liner, go with:

list2 = map(lambda el: el.split(","), flat_list)
list3 = [float(el) for sublist in list2 for el in sublist]

or

import itertools
list2 = map(lambda el: el.split(","), flat_list)
list3 = list(map(float, itertools.chain.from_iterable(list2)))

CodePudding user response:

I see that the coordinates come in pairs, so in order to convert them to an integer or float first we need to split them so they become single numbers.

    flat_list =['53295,-46564.2', '53522.6,-46528.4', '54792.9,-46184', '55258.7,-46512.9', '55429.4,-48356.9', '53714.5,-50762.8']
coordinates = []
for pair in flat_list:
    coordinates.extend(pair.split(','))
result = [float(x) for x in coordinates]

This is not the shortest way to do it, but I think it does the job.

  • Related