PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] What does arr.sort(key=lambda x: (x[0],-x[1])) mean?

 November 03, 2022     arrays, lambda, list, python-3.x, sorting     No comments   

Issue

>>> arr=[[4,5],[4,6],[6,7],[2,3],[1,1]]
>>> arr.sort(key=lambda x:x[0]) #statement 1
>>> arr
[[1, 1], [2, 3], [4, 5], [4, 6], [6, 7]]
>>> arr.sort(key=lambda x:(x[0],-x[1])) #statement 2
>>> arr
[[1, 1], [2, 3], [4, 6], [4, 5], [6, 7]]

So, I can observe the difference between the execution of statement 1 and statement 2. I am aware that statement 1 sorts the list in ascending order of x[0]. But if we use, statement 2 then how the list is sorted?


Solution

lambda x:(x[0],-x[1])

this generates tuples of (the first element, negative of the second element)

When you sort 2-tuples, they are sorted based on

  1. The first element
  2. If the first elements are equal, then the second element

So

arr.sort(key=lambda x:(x[0],-x[1]))

Sorts the list arr based on:

  1. the first element
  2. if the first elements are equal, then based on the negative of the second element.

(that is why [4,6] is ahead of [4,5] since -6 < -5)



Answered By - rdas
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing