Search code examples
pythonlistsortingzip

Sorting two lists together in using python zip function


my question is a bit different than the basic sorting two lists together.

See this code for example:

list1=[3,4,2,1,6,1,4,9,3,5,8]
list2=['zombie','agatha','young','old','later','world',
       'corona','nation','domain','issue','happy']
srt=sorted(list(zip(list1,list2)),reverse=True)
print(srt)

The output comes out to be:

[(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), 
 (4, 'corona'), (4, 'agatha'), (3, 'zombie'), (3, 'domain'), 
 (2, 'young'), (1, 'world'), (1, 'old')]

Question:- As we can see, for the values which are same in list 1, the elements of my list 2 also get sorted alphabetically in descending order. What if I want to sort the list 1 in descending order, and after that, my list 2 elements in ascending order, for which the value of elements of list 1 is same, in some trivial way.


Solution

  • Use key function lambda k: (-k[0], k[1])):

    list1 = [3, 4, 2, 1, 6, 1, 4, 9, 3, 5, 8]
    list2 = ['zombie', 'agatha', 'young', 'old', 'later', 'world', 'corona', 'nation', 'domain', 'issue', 'happy']
    srt = sorted(zip(list1, list2), key=lambda k: (-k[0], k[1]))
    print(srt)
    

    Prints:

    [(9, 'nation'), (8, 'happy'), (6, 'later'), (5, 'issue'), (4, 'agatha'), (4, 'corona'), (3, 'domain'), (3, 'zombie'), (2, 'young'), (1, 'old'), (1, 'world')]