complex sort in python

In python sort can be made with list.sort() or sorted(). The former is method of list and the latter is

Differences between the former and the latter are

list.sort() sorted()
change in place. return None return copy

Both have keyword arguments, key and reverse. key takes function to sort.

This coding challenge requires to sort by two keys.

If you can make each element tuple, lambda function can help you with that.

This is my code that passed the challenge above.

    def sortByBits(self, arr: list) -> list:

        def func(bn):
            return len([ char for char in bn if char == '1'])

        barr = [ ( f'{i:b}', i ) for i in arr ]
        barr.sort(key=lambda x: ( func(x[0]), x[1] ) )
        arr = [ it for _, it in barr ]

        return arr

Here take a look at another guy's more elegant code

    def sortByBits(self, arr: List[int]) -> List[int]:
        return sorted(arr, key=lambda item: ( bin(item).count('1'), item) )

Here instead of making a func, this guy used str.count method, which makes code neater.

leetcode python sort