简体   繁体   中英

sorting a list of tuple by second element but if the second element of mutiple tuple matches then sort using the first element

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)]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM