Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sort list with parallel list

I have a list that is filled with HTML elements. I also have a list filled with date/times, which is parallel to the HTML list.

How can I sort the HTML list based on the time/date list? The time/date is in a timestamp format.

like image 976
Zeno Avatar asked Mar 12 '11 17:03

Zeno


3 Answers

You can use zip.

timestamps, elements = zip(*sorted(zip(timestamps, elements)))

The result will be two tuples which you can convert to lists if you prefer.

like image 61
Tugrul Ates Avatar answered Oct 08 '22 18:10

Tugrul Ates


Zip the two lists up into tuples, sort, then take the HTML back out of the tuple:

zipped = zip(timestamps, htmls)
zipped.sort()
sorted_htmls = [html for (timestamp, html) in zipped]
like image 45
Thomas Avatar answered Oct 08 '22 18:10

Thomas


Enumerate will give you a list of (index,item) tuples for each item in the list. You can sort this using the index to read the sort key from the timestamps list. Then peel off the html elements:

sorted_elems = [elem for i,elem in sorted(enumerate(html_elements), 
                                          key=lambda x:timestamps[x[0]])]

What could be simpler?

like image 37
PaulMcG Avatar answered Oct 08 '22 17:10

PaulMcG