Reputation: 25
i'm writing a function on Python 2.7.10 that reads a .txt file and makes a list out of the lines from the file which is then sorted by these parameters:
My code so far:
import operator #imported before function
INDEXArrivalHour = 4 #imported before function
inFile = open("services0604.txt", "r")
inFile = inFile.readlines()[7:]
servicesList = []
for line in inFile:
servicesList.append(line.rstrip().split(", "))
servicesList = sorted(servicesList, key = operator.itemgetter(INDEXArrivalHour))
return servicesList
the result from printing the function:
[
['Maria Conceicao'<-#driver name, '13-GH-88', 'John Tush', '11:30', '11:50'<-#hour her service ends, 'alfama', '30', 'charges'],
['Josefino Branco', '07-BB-99', 'Louis Amber', '11:05', '11:50', 'baixa', '45', 'terminates'],
['Dominique Bart', '04-TY-86', 'Sarah Lino', '11:10', '12:10', 'lumiar', '80', 'terminates'],
['Tiago Quaresma', '17-VI-90', 'Paulo Silva', '12:05', '12:30', 'alvalade', '30', 'terminates']
]
By the second parameter the first list should come after the second list. I've tried using two separated sorted()'s but it does not do the job, i've played around with "key = " but i'm really stuck and out of ideas. I'd highly appreciate if someone could help me
Upvotes: 0
Views: 35
Reputation: 388313
Sorting twice but separately will not work correctly, as you will throw away the results from the first sorting.
Instead, sort by two properties directly:
servicesList.sort(key=lambda x: (x[4], x[0]))
This will use a tuple (x[4], x[0])
for each item to determine the sorting. x[4]
is the time, and x[0]
is the name.
Upvotes: 1