Home > front end >  how to sort 2d list in python using column 1
how to sort 2d list in python using column 1

Time:10-19

I have a list arr = [[1,2],[3,4],[0,6],[5,7],[8,9],[5,9]] i want to sort it in increasing order by it's column 1. my expected Output should be Output : [[1, 2], [3, 4], [0, 6], [5, 7], [5, 9], [8, 9]]

How can I achive that? when the two numbers in column 1 is same , it should check column 0 then

I was trying it like this:

from operator import itemgetter
arr = [[1,2],[3,4],[0,6],[5,7],[8,9],[5,9]]
arr = sorted(arr, key=itemgetter(1))
print(arr)

But when the two elements are Equal on column1 it gives Output like it's Occurence.

Is there any Other way in Python to achieve this? Dictionary may do the job to store Pair like this but Dictionary can't hold Duplicate keys that's Why i am trying to achieve this by using 2D List..

CodePudding user response:

You can sort by "column 1" first, then by "column 0":

>>> sorted(arr, key=lambda item: (item[1], item[0]))
[[1, 2], [3, 4], [0, 6], [5, 7], [5, 9], [8, 9]]

This technique also extends well to larger sublists, in the case you still only want to round by certain items.

CodePudding user response:

You could use reversed:

sorted(arr, key=reversed)

As stated, this works in python 2.

In python 3, you could use operator.itemgetter:

sorted(arr, key=itemgetter(slice(None, None, -1))
#or
sorted(arr, key=itemgetter(slice(1, 0))

CodePudding user response:

Sort using a key lambda that reverses the value positions on each row:

arr = [[1,2],[3,4],[0,6],[5,7],[8,9],[5,9]]

arr.sort(key=lambda r:r[::-1])

print(arr)

[[1, 2], [3, 4], [0, 6], [5, 7], [5, 9], [8, 9]]
  • Related