Sorting Lists or Tuples of Lists or Tuples by an Element at a Specific Index
Consider a list or tuple of lists or tuples with data in a hierarchical structure. For instance:
data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)]
To sort this data by the second element of each subset, there are two common approaches: using the sorted() function or the sort() method in ascending order by default.
Using the sorted() function with a key function:
sorted_by_second = sorted(data, key=lambda tup: tup[1])
Using the sort() method with a key function:
data.sort(key=lambda tup: tup[1]) # sorts in place
To sort in descending order, the reverse=True argument can be added:
sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
data.sort(key=lambda tup: tup[1], reverse=True) # sorts in place
Regardless of whether lists or tuples are used in the original data structure, the key function effectively accesses the desired element at index 1 and performs the sorting accordingly.
The above is the detailed content of How to Sort Nested Lists or Tuples by a Specific Element's Index?. For more information, please follow other related articles on the PHP Chinese website!