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:
- 2nd tuple item (the
int
) in reverse order. - "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)]