How to Sort a Nested List Based on Inner List Elements?

Patricia Arquette
Release: 2024-11-15 08:23:02
Original
847 people have browsed it

How to Sort a Nested List Based on Inner List Elements?

Sorting Nested Lists Based on Inner List Elements

Nested lists are ubiquitous in programming, and handling them requires adept data manipulation techniques. One such scenario involves sorting the outer list based on specific indices within the inner lists. Fortunately, the following solutions offer effective ways to tackle this challenge:

Using itemgetter

The itemgetter function from the operator module provides a concise solution. It allows you to extract specific elements from each inner list and sort the outer list based on those extracted elements.

from operator import itemgetter

L = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
sorted(L, key=itemgetter(2))
# [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
Copy after login

Using a lambda function

Although slightly less efficient in this simple case, a lambda function can also accomplish the sorting:

sorted(L, key=lambda x: x[2])
# [[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
Copy after login

By leveraging itemgetter or a lambda function, you can effectively sort nested lists based on specific indices of their inner elements, thereby enhancing your data processing capabilities.

The above is the detailed content of How to Sort a Nested List Based on Inner List Elements?. 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