Search code examples
pythonlistsortingstability

Python Sorting Question


i need to sort the following list of Tuples in Python:

ListOfTuples = [('10', '2010 Jan 1;', 'Rapoport AM', 'Role of antiepileptic drugs as preventive agents for migraine', '20030417'), ('21', '2009 Nov;', 'Johannessen SI', 'Antiepilepticdrugs in epilepsy and other disorders--a population-based study of prescriptions', '19679449'),...]

My purpose is to order it by Descending year (listOfTuples[2]) and by Ascending Author (listOfTuples[2]):

sorted(result, key = lambda item: (item[1], item[2]))

But it doesn't work. How can i obtain sort stability?


Solution

  • def descyear_ascauth(atup):
      datestr = atup[1]
      authstr = atup[2]
      year = int(datestr.split(None, 1)[0])
      return -year, authstr
    
    ... sorted(result, key=descyear_ascauth) ...
    

    Notes: you need to extract the year as an integer (not as a string), so that you can change its sign -- the latter being the key trick in order to satisfy the "descending" part of the specifications. Squeezing it all within a lambda would be possible, but there's absolutely no reason to do so and sacrifice even more readability, when a def will work just as well (and far more readably).