0

I would like to combine two sort conditions but one is ascending the other descending.

The input data are this list of tuples:

data = [
    ('Apple', 4),
    ('Cherry', 5),
    ('Ananas', 4),
    ('Blueberry', 3),
    ('Banana', 3)
]

The sorting conditions:

  1. 2nd tuple item (the int) in reverse order.
  2. "Inside" that sub groups: 1rst tuple item (the str) in regular lexicographic order.

The expected result should be

    ('Cherry', 5),
    ('Ananas', 4),
    ('Apple', 4),
    ('Banana', 3),
    ('Blueberry', 3),

I know that I can combine conditions like this:

sort(data, key=lambda x: condA(x[0]), condB(x[1]))

But my problem is that I don't know how to make one reverse the other not and how to do the lexicographic ordering in a lambda.

This is the MWE

#!/usr/bin/env python3
data = [
    ('Apple', 4),
    ('Cherry', 5),
    ('Ananas', 4),
    ('Blueberry', 3),
    ('Banana', 3)
]

expect = [
    ('Cherry', 5),
    ('Ananas', 4),
    ('Apple', 4),
    ('Banana', 3),
    ('Blueberry', 3),
]

result = sorted(data, key=lambda x: x[1], reverse=True)
print(result)
# [('Cherry', 5), ('Apple', 4), ('Ananas', 4), ('Blueberry', 3), ('Banana', 3)]

result = sorted(data, key=lambda x: x[0])
print(result)
# [('Ananas', 4), ('Apple', 4), ('Banana', 3), ('Blueberry', 3), ('Cherry', 5)]

# What I want.
print(expect)
# [('Cherry', 5), ('Ananas', 4), ('Apple', 4), ('Banana', 3), ('Blueberry', 3)]
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 1
    Since `.sort()` is *stable*, you don't HAVE to handle all the sort criteria at one time. You have the option of sorting by them individually, in increasing order of importance; this way, you can apply `reverse=True` or not to each individual sort. – jasonharper Jan 11 '23 at 16:33
  • I don't understand your comment. Vote for re-open because my question and MWE is of higher quality then the older one. Clearer and easier to understand. – buhtz Jan 11 '23 at 16:36

1 Answers1

1

This should work.

output = sorted(data, key=lambda x: (-x[1], x[0]))