DEV Community

Codes With Pankaj
Codes With Pankaj

Posted on

sort using python

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This solution uses the sort method with a custom key function to achieve the specified sorting criteria.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay