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.

2 Answers 2

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')]
Sign up to request clarification or add additional context in comments.

6 Comments

sorted can take any iterable so you can drop list: sorted(zip(list1, list2), key=lambda x, y: (-x, y)).
@LaurentLAPORTE Yes, good catch. Updated my answer.
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?
@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.
Oh, then how about descending for strings?
|
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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.