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']]
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))
The result will be:
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
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])
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!