Code Explanation:
Input Data:
data = [(1, 'b'), (3, 'a'), (2, 'c')]
This line creates a list of tuples named data. Each tuple contains two elements:
A number (e.g., 1, 3, 2).
A string (e.g., 'b', 'a', 'c').
Sorting the Data:
sorted_data = sorted(data, key=lambda x: x[1])
sorted(iterable, key):
sorted is a Python built-in function that returns a sorted version of an iterable (like a list) without modifying the original.
The key argument specifies a function to determine the "sorting criteria."
key=lambda x: x[1]:
A lambda function is used to specify the sorting criteria.
The input x represents each tuple in the data list.
x[1] extracts the second element (the string) from each tuple.
The list is sorted based on these second elements ('b', 'a', 'c') in ascending alphabetical order.
Printing the Sorted Data:
print(sorted_data)
This prints the sorted version of the data list.
Output:
[(3, 'a'), (1, 'b'), (2, 'c')]
0 Comments:
Post a Comment