What Loop Can I Use To Iterate So That I Can Get The Following Output?
Solution 1:
seems like your problem is that you use "first_station[1]"
as a string and not use its value.
try call
filter_routes(routes_data,first_station[1])
and
x = tuple([first_station[1]] + [a])
in addition, you use only your first station, I thing you meant to use ser
value, and another problem is that you return and quit the function before you finish, store the values in variable like `resultz here, and return it when you finish:
result= []
for entry in routes_data:
ser = entry[0]
a = filter_routes(routes_data,ser)
x = tuple([ser] + [a])
result.append(x)
returnresult
However I would write it this way:
defsplit_routes(routes_filename):
stations = {}
withopen(routes_filename,"r") as routes_data:
for line in routes_data:
vals = line.strip().split(",") # [’171’, ’1’, ’1’, ’59009’]
stations.setdefault(vals[0],[]).append(vals)
result = []
for st in stations:
result.append((st,stations[st]))
return result
and call it with the filename:
split_routes("bus_stations.txt")
Solution 2:
Here is one snippet that you can adapt for your use -
import fileinput
station_routes_map = {}
for line in fileinput.input():
route = line.strip().split(',')
first_station = route[0]
if first_station not in station_routes_map:
station_routes_map[first_station] = []
station_routes_map[first_station].append(route)
output = [(key, value) for key, value in station_routes_map.items()]
This basically stores the output that you desire in the output variable. You can adapt it for your function. Might need a fix here and there, since I haven't tested it, but overall it should run.
UPDATE
Ok, let me explain. The file you have is in the format -
first_station, .....rest_of_the_route....
What you are looking for, is a list of tuples that have first station as the first param, followed by the list of all routes that begin with that first station.
What this code does is -
- uses the fileinput module to read from your file, from command line (let's say)
- splits the line on ',', and uses the first nibble as first_station
- the station_routes_map dictionary is used to store the first_station as a key, and a list of routes as its value.
- for every line, it figures out the first_station and then add the route to an appropriate list in the station_route_map (using first_station as the key)
After building the map, it just uses list-comprehension to prepare a list of tuples from the dictionary by iterating over all its items.
Post a Comment for "What Loop Can I Use To Iterate So That I Can Get The Following Output?"