sort using python
Codes With Pankaj
Posted on November 24, 2023
Question:
You are given a list of tuples, each containing a string and an integer. Your task is to sort the list based on the string in descending order, and if two strings are the same, sort them based on the integer in ascending order. Implement a Python function to achieve this.
def custom_sort(input_list):
# Your code here
# Example usage:
input_list = [('apple', 3), ('banana', 1), ('orange', 2), ('apple', 1), ('banana', 2)]
result = custom_sort(input_list)
print(result)
Solution:
def custom_sort(input_list):
# Sort based on string in descending order, then by integer in ascending order
input_list.sort(key=lambda x: (x[0], -x[1]), reverse=True)
return input_list
# Example usage:
input_list = [('apple', 3), ('banana', 1), ('orange', 2), ('apple', 1), ('banana', 2)]
result = custom_sort(input_list)
print(result)
This solution uses the sort
method with a custom key function to achieve the specified sorting criteria.
๐ ๐ช ๐
๐ฉ
Codes With Pankaj
Posted on November 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.