Home > Net >  Convert a String into a List of Tuples
Convert a String into a List of Tuples

Time:01-19

I want to write a function that receives a string as a parameter and then converts it into a list of tuples.

String with dummy data:

locations_data = """
NewYork 37.936389°N 23.947222°E
London  37.936389°N 23.947222°E
Berlin  37.936389°N 23.947222°E
Milano  37.936389°N 23.947222°E

So far I know that I have to loop over the string splitter by °E but I'm getting confused when I have to separate each "rows" data.

for i in locations_data.split("°E")

Desired output:

locations = [
(NewYork, 37.936389, 23.947222),
(London, 37.936389, 23.947222),
(Berlin, 37.936389, 23.947222),
(Milano, 37.936389, 23.947222)
]

CodePudding user response:

Use split() to split each line into 3 fields. Remove the degree symbols and convert them to floats, then put them into tuples.

import re

locations = []
for line in locations_data.splitlines():
    city, lat, lon = line.split()
    lat = float(re.sub(r'°[NS]$', '', lat))
    lon = float(re.sub(r'°[EW]$', '', lon))
    locations.append((city, lat, lon))

CodePudding user response:

I would use a regex. Then you have several options:

re.split:

import re
[re.split('(?:°[NSEW])?\s ', s) for s in locations_data.splitlines()]

re.findall:

import re
re.findall('(\w )\s ([\d.] ).. ([\d.] )..', locations_data)

output:

[('NewYork', '37.936389', '23.947222'),
 ('London', '37.936389', '23.947222'),
 ('Berlin', '37.936389', '23.947222'),
 ('Milano', '37.936389', '23.947222')]

to have floats:

[(a, float(b), float(c))
 for a,b,c in re.findall('(\w )\s ([\d.] ).. ([\d.] )..', locations_data)]

output:

[('NewYork', 37.936389, 23.947222),
 ('London', 37.936389, 23.947222),
 ('Berlin', 37.936389, 23.947222),
 ('Milano', 37.936389, 23.947222)]

CodePudding user response:

Dirty but effective

lines = locations_data.split('\n')
locations = []

for line in lines:
    if len(line) > 0:
        my_tuple = ()
        
        for val in line.split(' '):
            if len(val) > 0:
                my_tuple = my_tuple   (val.replace('°N','').replace('°E',''),)

        locations.append(my_tuple)

print(locations)
# [('NewYork', '37.936389', '23.947222'), ('London', '37.936389', '23.947222'), ('Berlin', '37.936389', '23.947222'), ('Milano', '37.936389', '23.947222')]
  •  Tags:  
  • Related