16

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.

Zeno
  • 1,769
  • 7
  • 33
  • 61

4 Answers4

24

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.

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
  • @Thomas — Don't feel bad! `sort()` is in-place, while `sorted()` creates a new list, so `sort()` it typically what you want for big lists anyway. :-) – Ben Blank Mar 12 '11 at 17:53
  • Thanks. What about backwards? – Zeno Mar 12 '11 at 18:12
  • it is very strange that the same function can zip and unzip values. This makes it hard to understand the function. – canbax May 19 '19 at 09:51
  • zip does not unzip, but the * unpacks the sorted zip object, which is then again zipped by zip. – Epsilon Feb 22 '20 at 16:54
8

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]
Thomas
  • 174,939
  • 50
  • 355
  • 478
2

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?

PaulMcG
  • 62,419
  • 16
  • 94
  • 130
1

You can use a third-party package called more_itertools:

import more_itertools 

timestamps = ["08-11-17", "01-13-17", "11-22-17"]
elements = ["<p>", "<b>", "<a href>"]
more_itertools.sort_together([timestamps, elements])
# [('01-13-17', '08-11-17', '11-22-17'), ('<b>', '<p>', '<a href>')]

See more_itertools docs for more information.

pylang
  • 40,867
  • 14
  • 129
  • 121