Search code examples
pythonpython-3.xlistfolium

Is there a way to remove the 'quotes' a Python list has when reading from a file?


I am working with Python, using the Folium library. I want to read GPS coordinates (lat, long) from a .txt and throw it on a list. The problem is, the list I have right now comes out being:

['(-27.414, -48.518)', '(-27.414, -48.517)', '(-27.413, -48.517)', '(-27.412, -48.517)', '(-27.412, -48.516)', '(-27.411, -48.516)']

But when I want to use each item from the last as a location, I have an error:

ValueError: Expected two (lat, lon) values for location, instead got: '(-27.414, -48.518)'

Is there any way of changing my list so those 'quotes' disappear?

I have tried:

list(map(int, coordinatesList))
'[%s]' % ', '.join(map(str, coordinatesList))

But to no avail, on both of those, the list isn't a list anymore and if I try to access the first item, it returns '['.

On my .txt, each line is a coordinate set (lat, long), with no parentheses and separated by a comma. I have a function:

def criaListaDeCoordenadas(caminhoArquivo):
    coordenadasLidas = []
    with open(caminhoArquivo) as arquivo:
        temp = []
        for latLong in arquivo:
            if latLong.strip():
                temp.append(latLong.strip())
                for i in temp:
                    i = '(' + i + ')'
                    if i not in coordenadasLidas:
                        coordenadasLidas.append(i)
    return coordenadasLidas

Which returns ['(-27.414, -48.518)', '(-27.414, -48.517)', '(-27.413, -48.517)', '(-27.412, -48.517)', '(-27.412, -48.516)', '(-27.411, -48.516)'], but I want it to return [(-27.414, -48.518), (-27.414, -48.517), (-27.413, -48.517), (-27.412, -48.517), (-27.412, -48.516), (-27.411, -48.516)], while still being a list. The return of that function is to be used on folium.Marker().


Solution

  • You are creating a string representation of a tuple, rather than creating an actual tuple, to add to your list. Do something like

    import re
    
    
    def criaListaDeCoordenadas(caminhoArquivo):
        coordenadasLidas = []
        with open(caminhoArquivo) as arquivo:
            temp = []
            for lat_long_str in arquivo:
                lat_long = [float(x) for x in re.split(r',\s*', lat_long_str)]
                coordenadasLidas.append(tuple(lat_long))
        return coordenadasLidas