I have the below code:
JavaScript
x
4
1
lst = [['candy','30'], ['apple','10'], ['baby','20'], ['baby','10']]
2
lst.sort(key=lambda x: (x[1], x[0]))
3
print(lst)
4
With this the output is:
JavaScript
1
2
1
[['apple', '10'], ['baby', '10'], ['baby', '20'], ['candy', '30']]
2
I’m trying to display the names in Descending order while the values in Ascending order. Is there a pre built way in python to achieve this?
Expected output:
JavaScript
1
2
1
[['baby', '10'], ['apple', '10'], ['baby', '20'], ['candy', '30']]
2
Advertisement
Answer
You changed the expected output, this would be the solution for that:
JavaScript
1
3
1
lst.sort(key=lambda x: (-int(x[1]), x[0]), reverse=True)
2
#[['baby', '10'], ['apple', '10'], ['baby', '20'], ['candy', '30']]
3
This was the answer before the question was edited and seperates the entries before sorting them:
JavaScript
1
3
1
print(*zip(sorted([x[0] for x in lst], reverse=True), sorted([x[1] for x in lst])))
2
# ('candy', '10') ('baby', '10') ('baby', '20') ('apple', '30')
3