gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
I have list of this format: [['a', 11], ['on', 5], ['of', 5]]. I want to sort it wo it…
- User
I have list of this format: [['a', 11], ['on', 5], ['of', 5]]. I want to sort it wo it would become [['a', 11], ['of', 5], ['on', 5]]. How do I do that? (by alphabet if second numbers in equal)
- Assistant
You can use a lambda function as the key for the
sortedfunction to specify the sorting order. Here's an example:my_list = [['a', 11], ['on', 5], ['of', 5]] sorted_list = sorted(my_list, key=lambda x: (-x[1], x[0])) print(sorted_list) # output: [['a', 11], ['of', 5], ['on', 5]]Explanation:
- The
keyargument takes a function that returns a value to be used as the sort key. In this case, we're using a lambda function that takes a listxas input and returns a tuple with two values. - The
-x[1]part is used to sort the list in descending order of the second elements (i.e., the numbers). The negative sign is used to reverse the order so that the largest numbers come first. - The
x[0]part is used to break ties by sorting the words in ascending order.
- The