Hi all,

I have a list called count_list which contains tuples like below:

[('bridge', 2), ('fair', 1), ('lady', 1), ('is', 2), ('down', 4),
> ('london', 2), ('falling', 4), ('my', 1)]

I want to sort it based on the second parameter in descending order and the
tuples with the same second parameter must be sorted based on their first
parameter, in alphabetically ascending order. So the ideal output is:

[('down', 4), ('falling', 4), ('bridge', 2), ('is', 2), ('london', 2),
> ('fair', 1), ('lady', 1), ('my', 1)]

What I ended up doing is:

count_list = sorted(count_list,
>                     key=lambda x: (x[1], map(lambda x: -x, map(ord,
> x[0]))),
>                     reverse=True)

which works. Now my solution is very specific to structures like [(str,
int)] where all strs are lower case and besides ord makes it to be both
limited in use and also more difficult to add extra levels of sorting.

The main problem is that reverse argument takes only a boolean and applies
to the whole list after sorting in finished. I couldn't think of any other
way (besides mapping negative to ord values of x[0]) to say reverse on the
first level but not reverse on the second level. Something like below would
be ideal:

count_list = sorted(count_list,
>                     key=lambda x: (x[1], x[0]),
>                     reverse=(True, False))

Does such a way similar to above exist? If not, how useful would it be to
implement it?

*P.S.* It's my first time on a mailing list. I apologize before hand if
such a thing has already been discussed or even there exist a way which
already achieves that.
Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to