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.
Top comments (0)