Python: Sort list of lists numerically

  • A+
Category:Languages

I have a list of x,y coordinates that I need to sort based on the x coordinate, then y coordinate when x is the same and eliminate duplicates of the same coordinates. For example, if the list is:

[[450.0, 486.6], [500.0, 400.0], [450.0, 313.3], [350.0, 313.3], [300.0, 400.0],   [349.9, 486.6], [450.0, 313.3]] 

I would need to rearrange it to:

[[300.0, 400.0], [349.9, 486.6], [350.0, 313.3], [450.0, 313.3], [450.0, 486.6],  [500.0, 400.0]] 

(with one duplicate of [450.0, 313.3] removed)

 


That is the normal sort order for a list of lists, anyway. De-dupe it with a dict.

>>> L = [[450.0, 486.6], [500.0, 400.0], [450.0, 313.3], [350.0, 313.3], [300.0, 400.0], [349.9, 486.6], [450.0, 313.3]] >>> sorted({tuple(x): x for x in L}.values()) [[300.0, 400.0],  [349.9, 486.6],  [350.0, 313.3],  [450.0, 313.3],  [450.0, 486.6],  [500.0, 400.0]] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: