Home > Backend Development > Python Tutorial > How Can I Efficiently Sort a List Based on Multiple Attributes in Python?

How Can I Efficiently Sort a List Based on Multiple Attributes in Python?

DDD
Release: 2024-12-11 18:02:13
Original
343 people have browsed it

How Can I Efficiently Sort a List Based on Multiple Attributes in Python?

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]]
Copy after login

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])
Copy after login

Using this key function, the list can be sorted as follows:

s = sorted(s, key=key)
Copy after login

Alternatively, itemgetter() can be employed to achieve the same result more efficiently:

import operator
key = operator.itemgetter(1, 2)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template