简体   繁体   中英

Printing a list within a list as a string on new lines

I'm really struggling with this issue, and can't seem to find an answer anywhere. I've got a text file which has name of the station and location, the task is to print out the names of the stations all underneath each other in order and same for the locations.
In my text file the names of the stations are always made up of two words and the location is 3 words.

text_file = "London Euston 12 London 56, Aylesbury Vale 87 Parkway 99, James Cook 76 University 87, Virginia Water 42 Surrey 78"

Desired outcome would be:

Stations:
London Euston
Aylesbury Vale
James Cook
Virginia Water

Locations:
12 London 56
87 Parkway 99
76 University 87
42 Surrey 78

my current code:

replaced = text_file.replace(","," ")
replaced_split = replaced.split()

i = 0
b = 2
stations = []
locations = []

while b < len(replaced_split):
   locations.append(replaced_split[b:b+3])
   b += 5

while i < len(replaced_split):
   stations.append(replaced_split[i:i+2])
   i += 5

for x in range(len(stations)):
   print(stations[x])

for y in range(len(locations)):
   print(dates[y])
The outcome I'm receiving is printing lists out:
['London', 'Euston']
['Aylesbury', 'Vale']
['James', 'Cook']
['Virginia', 'Water']
['12', 'London', '56']
['87', 'Parkway', '99']
['76', 'University', '87']
['42', 'Surrey', '78']

This is a simple a straight forward approach using for-loop instead of while loop.
What the code does: It splits your string into substrings, where every substring is separated by comma and space. After that it splits those substrings again by space then joins the first two elements of each substring to create station and appends it to the stations list, and finally the rest of the substring leaving the first two elements as the location and appends that to the locations list. Now you loop the lists to print their elements

stations = []
locations = []

for char in text_file.split(", "):
    parts = char.split(" ")
    stations.append(" ".join(parts[:2]))
    locations.append(" ".join(parts[2:]))


print("Stations:")
for station in stations:
    print(station)

print("\nLocations:") 
for location in locations:
    print(location)


Stations:
London Euston
Aylesbury Vale
James Cook
Virginia Water

Locations:
12 London 56
87 Parkway 99
76 University 87
42 Surrey 78

Instead of simply printing the list try joining the list first, like so:

print(' '.join(stations[x]))

You could even shorten the whole loop from this:

for x in range(len(stations)):
   print(stations[x])

to this:

print('\n'.join(' '.join(station) for station in stations))

Instead of manually processing the string, regular expressions can come in handy here. First split the text_file to one line per input, then use two capturing groups to fetch the station and location of each input. We store the stations and locations in two arrays and print them out at the end.

import re

text_file = "London Euston 12 London 56, Aylesbury Vale 87 Parkway 99, James Cook 76 University 87, Virginia Water 42 Surrey 78"

prog = re.compile(r'(\w+\s\w+)\s(\d+\s\w+\s\d+)')
lines = text_file.split(', ')
stations = []
locations = []

for line in lines:
    result = prog.match(line)
    stations.append(result.group(1))
    locations.append(result.group(2))

print("Stations:")
for s in stations:
    print(s)
print("\nLocations")
for l in locations:
    print(l)

What you're doing works and arranges the data like you want. You just need to print it properly, by join ing the lists. In your existing code, if you change to:

print(' '.join(stations[x]))

and:

print(' '.join(dates[y]))

You will get your desired output.


But you could simplify a bit the logic if the strings are always structured like you say:

text_file = "London Euston 12 London 56, Aylesbury Vale 87 Parkway 99, James Cook 76 University 87, Virginia Water 42 Surrey 78"
places = text_file.split(', ')

stations, locations = [], []
for place in places:
    parts = place.split()
    stations.append(' '.join(parts[:2]))
    locations.append(' '.join(parts[2:]))

print("Stations:")
for station in stations:
    print(station)

print("Locations:")
for location in locations:
    print(location)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM