Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sort of a list of tuples

I only started learning Python few days ago, and I wanted to implement my little project in it. I need to sort a list of (string, integer) in a descending order by the number value, but alphabetically if the number is the same for more than one tuple. So I have a list, say:

tuples = [('ggg', 5), ('aaa', 5), ('bbb', 6), ('zzz', 6)]
tuples.sort(key=lambda score: score[1], reverse=True)

This returns:

[('bbb', 6), ('zzz', 6), ('ggg', 5), ('aaa', 5)]

But what I want to get is:

[('bbb', 6), ('zzz', 6), ('aaa', 5), ('ggg', 5)]

In Java I just implemented a comparator for a custom tuple:

class Pair {
    public final String s;
    public final Integer i;

    public Pair(String s, Integer i) {
        this.s = s;
        this.i = i;
    }
}

class PairComparator implements Comparator<Pair> {

    @Override
    public int compare(Pair p1, Pair p2) {
        int c = p1.i.compareTo(p2.i);
        return (c == 0) ? p1.s.compareTo(p2.s) : c * (-1);
    }
}

But I'm not sure how to go about doing that in a lambda expression in Python.

like image 720
shooqie Avatar asked Jan 31 '26 02:01

shooqie


1 Answers

Perhaps the simplest way would be have key return a tuple and multiply the score by -1. For example:

>>> tuples.sort(key=lambda x: (-x[1], x[0]))
>>> tuples
[('bbb', 6), ('zzz', 6), ('aaa', 5), ('ggg', 5)]

This will sort the integers in descending order and then the strings in ascending order.

like image 88
Alex Riley Avatar answered Feb 01 '26 16:02

Alex Riley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!