Python: Sort a given list of strings(numbers) numerically using lambda
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.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics