Home >Backend Development >Python Tutorial >How Can Sorting Keys Efficiently Sort Lists Based on Multiple Attributes?

How Can Sorting Keys Efficiently Sort Lists Based on Multiple Attributes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 19:51:11707browse

How Can Sorting Keys Efficiently Sort Lists Based on Multiple Attributes?

Utilizing Sorting Keys for Multi-Attribute Sorting of Lists

Sorting a list of lists based on individual attributes is often straightforward. However, when multiple attributes are involved, a dilemma arises. Can we sort efficiently without multiple rounds of sorting?

To address this challenge, we introduce the concept of sorting keys. A sorting key acts as a function that assigns a unique value to each element in the list, determining the sorting order.

For instance, in the given list:

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

To sort by both "tall/short" and "color," we can define a key function that returns a tuple based on these attributes:

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

Using this key, we can sort the list using the sorted function:

s = sorted(s, key = key)

Alternatively, we can leverage the itemgetter function for faster performance:

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

Furthermore, we can directly sort the list using the sort function with the specified key:

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

With sorted keys, we achieve efficient multi-attribute sorting without the need for multiple sorting passes.

The above is the detailed content of How Can Sorting Keys Efficiently Sort Lists Based on Multiple Attributes?. 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
Previous article:Task-Python PackagesNext article:Task-Python Packages