3

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.

ywbaek
  • 2,971
  • 3
  • 9
  • 28
Rishabh Rao
  • 139
  • 2
  • 6

2 Answers2

4

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')]
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    `sorted` can take any iterable so you can drop `list`: `sorted(zip(list1, list2), key=lambda x, y: (-x, y))`. – Laurent LAPORTE Jun 29 '20 at 17:27
  • @LaurentLAPORTE Yes, good catch. Updated my answer. – Andrej Kesely Jun 29 '20 at 17:28
  • Thanks, that worked. one query, so -k[0] implies descending order for first list, and k[1] means ascending order for second list, right? Hope my intuition is correct? – Rishabh Rao Jun 29 '20 at 18:05
  • @RishabhRao Yes, that's true, `-k[0]` is descending by first element, `k[1]` ascending by second element. Note: the minus sign works only for numerical data. – Andrej Kesely Jun 29 '20 at 18:06
  • Oh, then how about descending for strings? – Rishabh Rao Jun 29 '20 at 18:09
  • @RishabhRao That's a little bit more complicated. Look for example here: https://stackoverflow.com/questions/42916223/sorting-a-tuple-of-strings-alphabetically-and-reverse-alaphabetically – Andrej Kesely Jun 29 '20 at 18:12
0

It's not pretty but you could do a "double" sorted(), first by the list2 value then reversed list1 value:

from operator import itemgetter

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(sorted(zip(list1,list2), key=itemgetter(1)), key=itemgetter(0), reverse=True)
print(srt)

Output:

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