Python: Sort list with parallel list

前端 未结 4 1401
渐次进展
渐次进展 2021-02-19 09:42

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

相关标签:
4条回答
  • 2021-02-19 10:07

    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.

    0 讨论(0)
  • 2021-02-19 10:08

    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?

    0 讨论(0)
  • 2021-02-19 10:11

    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.

    0 讨论(0)
  • 2021-02-19 10:19

    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]
    
    0 讨论(0)
提交回复
热议问题