Home > Mobile >  sorting a list of tuple by second element but if the second element of mutiple tuple matches then so
sorting a list of tuple by second element but if the second element of mutiple tuple matches then so

Time:08-18

Given a list of tuples where first and second elements are integer. Sort them using the second element but if the second element matches sort them using first element. Basically, I am trying to convert c pair<int, int> type comparison to python code. This is the c version.

bool cmp(const pair<int,int>& a, const pair<int,int>& b)
{
    if(a.second != b.second) return a.second < b.second;
    return a.first < b.first;
}

int main() {
   //some code here

   sort(v.begin(), v.end(), cmp);

   //some code here

   return 0;
}

this code produces,

input: [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]

output: [(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]

I tried to convert that code in python

sil = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]

sil.sort(key = lambda y : y[1])

But sadly this only produces output: [(2, 5), (1, 5), (3, 6), (6, 9), (8, 10)]. Clearly, (1, 5) should come before (2, 5) but it didn't happen.

My question is how to implement this in python so the output should be [(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]

CodePudding user response:

You can specify both the elements in the key -

inp = [(2, 5), (3, 6), (1, 5), (8, 10), (6, 9)]
sorted(inp, key=lambda x: (x[1], x[0]))

Output

[(1, 5), (2, 5), (3, 6), (6, 9), (8, 10)]
  • Related