Home > Backend Development > Python Tutorial > How to Sort a List of Lists Based on a String Field in Python?

How to Sort a List of Lists Based on a String Field in Python?

Patricia Arquette
Release: 2024-11-26 18:18:10
Original
985 people have browsed it

How to Sort a List of Lists Based on a String Field in Python?

Sorting Lists by Inner List's String Field

In Python, you can manipulate lists with ease, including sorting based on specific indices of the inner lists.

Consider the following list of lists:

L = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
Copy after login

If we want to sort the outer list based on the string field of the inner lists, we can utilize the itemgetter function from the operator module.

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

The result will be:

[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
Copy after login

The itemgetter function effectively fetches the third element (index 2) from each inner list and sorts the outer list based on these values.

Alternatively, you can use a lambda function for the same purpose, although it may be slightly less efficient in this specific case:

sorted(L, key=lambda x: x[2])
Copy after login

The above is the detailed content of How to Sort a List of Lists Based on a String Field 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