devblack.exe
devblack.exe

Reputation: 584

Convert a String into a List of Tuples

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)
]

Upvotes: 0

Views: 163

Answers (4)

Kavindu Nilshan
Kavindu Nilshan

Reputation: 811

You can use this way to solve the problem.

locations = list(map(lambda x: tuple(x.split()), locations_data.split("°E")[:4]))
print(locations)

locations_data.split("°E")[:4] here this [:4] part is use to remove the last empty string.

Upvotes: 3

Kaz Miller
Kaz Miller

Reputation: 979

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')]

Upvotes: 1

mozway
mozway

Reputation: 260725

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)]

Upvotes: 1

Barmar
Barmar

Reputation: 781059

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))

Upvotes: 2

Related Questions