Python Forum
Conditional sorting in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Conditional sorting in Python
#1
In Python how can i sort a two item list based on the condition: if first items are not equal do a normal sort (based on the values of first items), and if the first items are equal sort base on the biggness of second items (the bigger value comes first):

Keys of a dictonary like this:

{(0, 3): (3, 8), (0, 11): (4, 4), (1, 4): (5, 32)}

should be then sorted as such:

[(0, 11), (0, 3), (1, 4)]
Reply
#2
data = {(0, 3): (3, 8), (0, 11): (4, 4), (1, 4): (5, 32)}
print(sorted(sorted(data.keys(), key=lambda x: x[1], reverse=True), key=lambda x:x[0]))
[(0, 11), (0, 3), (1, 4)]

https://wiki.python.org/moin/HowTo/Sorti...plex_Sorts
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python 2 to 3 dict sorting joshuaprocious 2 53,717 May-14-2020, 03:28 PM
Last Post: joshuaprocious
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 2,997 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  Python - sorting algorithms hrca 3 3,112 Nov-06-2018, 07:06 PM
Last Post: hrca
  Sorting values calculated in python stumunro 4 3,901 Sep-13-2017, 06:09 AM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020