Home >Backend Development >Python Tutorial >How Can I Efficiently Sort Lists with Multiple Attributes in Python?

How Can I Efficiently Sort Lists with Multiple Attributes in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 17:05:17435browse

How Can I Efficiently Sort Lists with Multiple Attributes in Python?

Effective Sorting of Lists with Multiple Attributes

When managing lists of lists, it becomes necessary to efficiently sort them based on specific attributes. A common scenario arises when we need to sort by multiple attributes simultaneously, such as sorting a list of colors and heights.

Consider the following list of lists:

[[12, 'tall', 'blue', 1],
[2, 'short', 'red', 9],
[4, 'tall', 'blue', 13]]

Ordinarily, sorting by a single attribute can be achieved using sorted(s, key = itemgetter(1)). However, for multiple attributes, a more efficient approach exists.

A key can be defined as a function that returns a tuple. By using a lambda function or itemgetter, we can create a key that considers multiple attributes:

Lambda Function:

s = sorted(s, key = lambda x: (x[1], x[2]))

Using Itemgetter (Faster):

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

Additionally, the sort method can be used directly with the provided key:

s.sort(key = operator.itemgetter(1, 2))

With this approach, the list will be effectively sorted based on the specified attributes. This method is considerably faster and avoids unnecessary Python function calls.

The above is the detailed content of How Can I Efficiently Sort Lists with Multiple Attributes in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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