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']]
Explanation:
In the above code:
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']]
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!