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
Release: 2024-12-09 19:51:11
Original
658 people have browsed it

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

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

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

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

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

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template