Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by given order of indices

I have a list of lines read from a file. I need to sort the list by time stamp. I have parsed out the time stamp using regular expressions and place them into a separate list. The indices of the two lists will match. Once I sort the list of time stamps, I can get the order of indices.

Is there a way to apply the same order of indices to the original list of lines? The result should be the sorted list of original lines.

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]
like image 406
Hannah Avatar asked Jul 15 '10 21:07

Hannah


People also ask

How do you sort a list from a specific index in Python?

sort() can be used to perform this variation of sort by passing a function as a key that performs the sorting according to the desired inner list index. This can also be applied to perform this particular task. The advantage that it holds is that it does not modify the original list.

How do you sort a list by order in Python?

Sort with custom function using key If you want your own implementation for sorting, the sort() method also accepts a key function as an optional parameter. Based on the results of the key function, you can sort the given list. Here, len is Python's in-built function to count the length of an element.

How do I sort an array from a specific index?

sort(long[], int, int) method sorts the specified range of the specified array of longs into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.


2 Answers

[listofLines[i] for i in sortedIndex]
like image 108
sepp2k Avatar answered Oct 15 '22 05:10

sepp2k


I think you could do

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

But if you have (or could write) a function to automatically extract the time from the line,

def extract_time(line):
    ...
    return time

you could also do

listofLines.sort(key=extract_time)

or if you want to keep the original list intact,

sorted(listofLines, key=extract_time)
like image 24
David Z Avatar answered Oct 15 '22 05:10

David Z