Home > other >  Python: Fill data in a list in a tuple
Python: Fill data in a list in a tuple

Time:01-17

I need to create a function that reads the data given and creates a list that contains tuples each of which has as its first element the name of the airport and as its second and third its geographical coordinates as float numbers.

airport_data = """
Alexandroupoli 40.855869°N 25.956264°E
Athens 37.936389°N 23.947222°E
Chania 35.531667°N 24.149722°E
Chios 38.343056°N 26.140556°E
Corfu 39.601944°N 19.911667°E
Heraklion 35.339722°N 25.180278°E"""

airports = []

import re
airport_data1 = re.sub("[°N@°E]","",airport_data)
        
def process_airports(string):
    airports_temp = list(string.split())
    airports = [tuple(airports_temp[x:x 3]) for x in range(0, len(airports_temp), 3)]
    return airports

print(process_airports(airport_data1))

This is my code so far but I'm new to Python, so I'm struggling to debug my code.

CodePudding user response:

If you want the second and third element of the tuple to be a float, you have to convert them using the float() function. One way to do this is creating a tuple with round brackets in your list comprehension and convert the values there:

    def process_airports(string):
        airports_temp = string.split()
        airports = [(airports_temp[x], float(airports_temp[x 1]), float(airports_temp[x 2])) for x in range(0, len(airports_temp), 3)]
        return airports

This yields a pretty unwieldy expression, so maybe this problem could be solved more readable with a classical for loop.

Also note that slpit() already returns a list. Further remark: If you just cut off the letters from coordinates this might come back to bite you when your airports are in different quadrants.

CodePudding user response:

You need to take in account N/S, W/E for longitude and latitude. May be

def process_airports(string):
    airports = []
    for line in string.split('\n'):
        if not line: continue
        name, lon, lat = line.split()
        airports.append((name,
                         float(lon[:-2]) * (1 if lon[-1] == "N" else -1),
                         float(lat[:-2]) * (-1 if lat[-1] == "E" else 1)
                       ))
    return airports
        
>>> process_airports(airport_data1)
[('Alexandroupoli', 40.855869, -25.956264), ('Athens', 37.936389, -23.947222), ('Chania', 35.531667, -24.149722), ('Chios', 38.343056, -26.140556), ('Corfu', 39.601944, -19.911667), ('Heraklion', 35.339722, -25.180278)]

I prefered the double split to put in evidence the differences lines/tuple elements

  •  Tags:  
  • Related