w3resource

Python: Sort a given list of strings(numbers) numerically using lambda

Python Lambda: Exercise-48 with Solution

Write a Python program to sort a given list of strings (numbers) numerically using lambda.

Sample Solution:

Python Code :

# Define a function 'sort_numeric_strings' that sorts a list of strings containing numeric values
def sort_numeric_strings(nums_str):
    # Sort the 'nums_str' list using the 'sorted' function with a key function
    # The key function converts each element to an integer using 'int' and sorts them numerically
    result = sorted(nums_str, key=lambda el: int(el))
    
    # Return the sorted list of numeric strings
    return result

# Create a list of strings 'nums_str' containing numerical strings
nums_str = ['4', '12', '45', '7', '0', '100', '200', '-12', '-500']

# Print the original list of strings 'nums_str'
print("Original list:")
print(nums_str)

# Sort the list of strings numerically using the 'sort_numeric_strings' function and print the sorted result
print("\nSort the said list of strings (numbers) numerically:")
print(sort_numeric_strings(nums_str)) 

Sample Output:

Original list:
['4', '12', '45', '7', '0', '100', '200', '-12', '-500']

Sort the said list of strings(numbers) numerically:
['-500', '-12', '0', '4', '7', '12', '45', '100', '200']

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to sort a given mixed list of integers and strings using lambda. Numbers must be sorted before strings.

Next: Write a Python program to count the occurrences of the items in a given list using lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-48.php