Multi-Attribute List Sorting
Sorting a list based on a single attribute is straightforward. However, when multiple attributes dictate the sort order, a more complex approach is required.
Consider the following list of lists:
[[12, 'tall', 'blue', 1], [2, 'short', 'red', 9], [4, 'tall', 'blue', 13]]
Sorting this list solely by the 'tall' or 'short' attribute can be achieved using sorted(s, key = itemgetter(1)). However, if the sort order must be based on both the height and color attributes, a more efficient solution is necessary.
Multi-Attribute Key Functions
To sort a list by multiple attributes, a key function can be defined that returns a tuple representing the desired sort order. For instance, the following key function sorts by height first and then by color:
key = lambda x: (x[1], x[2])
Using this key function, the list can be sorted as follows:
s = sorted(s, key=key)
Alternatively, itemgetter() can be employed to achieve the same result more efficiently:
import operator key = operator.itemgetter(1, 2)
This key function is both faster and does not involve a Python function call.
Direct Sorting
Finally, the above approach can be simplified further by using the sort() method instead of sorted() and reassigning. This eliminates the need to create a new list:
s.sort(key=key)
The above is the detailed content of How Can I Efficiently Sort a List Based on Multiple Attributes in Python?. For more information, please follow other related articles on the PHP Chinese website!