In Python, you can usesorted()
Function or()
Method to correctObject array(such as a tuple or list in a list) sorted by the second value. Here are a few common methods:
1. Use the sorted() function (returns the new sorted list)
data = [{1, 2}, {2, 1}] # Note: Collections are unordered and cannot be sorted directly. Tuples or lists should be used here. # The correct data structure should be a list of tuples or listsdata = [(1, 2), (2, 1)] # or [[1, 2], [2, 1]] # Sort by second elementsorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data) # Output: [(2, 1), (1, 2)]
2. Use the() method (sort in place, not return the new list)
data = [(1, 2), (2, 1)] (key=lambda x: x[1]) print(data) # Output: [(2, 1), (1, 2)]
3. If the data structure is a set, the set itself is unordered and cannot be sorted directly. It needs to be converted to a tuple or a list first.
data = [{1, 2}, {2, 1}] # Convert a collection to a tuple or list and sort itsorted_data = sorted([tuple(s) for s in data], key=lambda x: x[1]) print(sorted_data) # Output: [(1, 2), (2, 1)] or [(2, 1), (1, 2)] because the order of the set is uncertain
Things to note
- gather(
set
) is disordered, so{1, 2}
and{2, 1}
is the same set, and the order cannot be distinguished. If order is required, tuples should be used (tuple
) or list (list
)。 -
key=lambda x: x[1]
Represents sorting by the second value of each element (index 1) (array subscript starts at 0).
Sample code (tuples or lists are recommended)
# Use Tuplesdata = [(1, 2), (2, 1), (3, 0)] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data) # Output: [(3, 0), (2, 1), (1, 2)] # Use listdata = [[1, 2], [2, 1], [3, 0]] (key=lambda x: x[1]) print(data) # Output: [[3, 0], [2, 1], [1, 2]]
If you do need to work with a collection, make sure to convert it to an ordered data structure (such as a tuple or a list) before sorting.
Extension: Inverse sorting
By default, followAscending orderFor sorting, if we need to sort in reverse order, we can add more parametersreverse=True
(This parameter is by defaultFalse
),For example:
data = [(1, 2), (2, 1), (3, 0)] sorted_data = sorted(data, key=lambda x: x[1], reverse=True) (key=lambda x: x[1], reverse=True)
This is the end of this article about the implementation of Python's method of sorting object arrays. For more related Python object array sorting content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!