Sorting a list by a given index order

I have a list of lines read from a file. I need to sort the list by timestamp. I checked the timestamp using regular expressions and put them on a separate list. The indices of the two lists will match. As soon as I sort the list of timestamps, I can get the index order.

Is there a way to apply the same index order to the original row list? The result should be a sorted list of source strings.

Example:

listofLines =  ['log opened 16-Feb-2010 06:37:56 UTC', 
                '06:37:58 Custom parameters are in use',
                'log closed 16-Feb-2010 05:26:47 UTC']
listofTimes = ['06:37:56', '06:37:58', '05:26:47']
sortedIndex = [2,0,1]
+5
source share
4 answers

I think you could do

[line for (time,line) in sorted(zip(listofTimes, listofLines))]

But if you have (or can write) a function to automatically extract time from a string,

def extract_time(line):
    ...
    return time

you can also do

listofLines.sort(key=extract_time)

,

sorted(listofLines, key=extract_time)
+4
[listofLines[i] for i in sortedIndex]
+18
sorted(zip(listofTimes, listofLines))
+2

If you want to sort the source list because you, say, stop linking to it elsewhere, you can assign it a sorted list:

my_list[:] = [my_list[i] for i in sorted_indexes]  # [:] is key!
0
source

All Articles