Home > Backend Development > Python Tutorial > How to Sort a List of Lists by a Specific Index in Python?

How to Sort a List of Lists by a Specific Index in Python?

Patricia Arquette
Release: 2024-11-25 10:49:12
Original
725 people have browsed it

How to Sort a List of Lists by a Specific Index in Python?

Sorting a List of Lists by an Index Using Python

Sorting a list of lists by a specific index of the inner list can be achieved in Python using the itemgetter operator from the operator module.

Problem Statement:

Given a list of lists, where each inner list contains three elements: two integers and a string, the objective is to sort the outer list based on the string value in the inner lists.

Solution:

The itemgetter operator can be applied to a list of lists using the key argument of the sorted function. This allows for specifying the index of the inner list that should be used for sorting.

Python Code:

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

Explanation:

In the above code:

  • from operator import itemgetter imports the itemgetter operator.
  • L is the provided list of lists.
  • sorted(L, key=itemgetter(2)) calls the sorted function to sort the list L. The key argument specifies the itemgetter(2) operator, which indicates that the string value (index 2) of each inner list should be used for sorting.

Alternatively, a lambda function can be used instead of itemgetter:

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

However, the itemgetter approach is generally more efficient in this scenario.

The above is the detailed content of How to Sort a List of Lists by a Specific Index 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template