Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I alphabetize data in a txt file to a list

txt file

Zurich, Sun, (8, 52)
Auckland, Sun, (20, 52)
Barcelona, Sun, (8, 52)
Vancouver, Sun, (0, 52)
Beirut, Sun, (9, 52)
Athens, Sun, (9, 52)
Amsterdam, Sun, (8, 520)
Toronto, Sun, (2, 52)
Vienna, Sun, (8, 52)
Winnipeg, Sun, (1, 52)
Atlanta, Sun, (2, 52)
Anchorage, Sat, (23, 52)
Warsaw, Sun, (8, 52)
Ankara, Sun, (10, 52)
Washington DC, Sun, (2, 52)

code:

list_aldskjfa = []
data = open('city_time.txt', 'r')
data = data.read()
list1 = []
for line in sorted(open('A1_cities_and_time.txt')):
    list1.append(line)
    print(line, end='')
print(list1)
output: ['Amsterdam, Sun, (8, 520)\n', 'Anchorage, Sat, (23, 52)\n', 'Ankara, Sun, (10, 52)\n', 'Athens, Sun, (9, 52)\n', 'Atlanta, Sun, (2, 52)\n', 'Auckland, Sun, (20, 52)\n', 'Barcelona, Sun, (8, 52)\n', 'Beirut, Sun, (9, 52)\n', 'Toronto, Sun, (2, 52)\n', 'Vancouver, Sun, (0, 52)\n', 'Vienna, Sun, (8, 52)\n', 'Warsaw, Sun, (8, 52)\n', 'Washington DC, Sun, (2, 52)', 'Winnipeg, Sun, (1, 52)\n', 'Zurich, Sun, (8, 52)\n']

As you can see, the list is alphabetized properly, with amsterdam, then anchorage, then ankara, etc. The problem is that the entire thing is a string – including the tuple and the date. The ideal output would look like [(‘Amsterdam’, ‘Sun’, (8,520)), (‘Anchorage’, ‘Sun’, (8,520)), etc.]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems as though what you need to do is split each entry of the list into a tuple. One nice solution is to use the parse module. Here’s a way to do it from scratch.

def sep(line):
    line = line.strip()
    parts = line.split(',')
    a = int(parts[2][2:])
    b = int(parts[3][1:-1])
    return (parts[0],parts[1][1:],a,b)

output = list(map(sep,list1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading