我们可以使用常规的排序函数对列表进行排序。这将按列表的第一个索引对列表进行排序。但是,比起通常情况,更常见的情况是需要通过其他索引元素对列表的列表进行排序。让我们讨论执行此任务的某些方法。
方法#1:使用sort()
+ lambda
通过将函数作为键传递给可以根据所需内部列表索引执行排序的函数,可以使用sort()
来执行排序的这种变化。
# Python 3 code to demonstrate
# to sort list of list by given index
# using sort() + lambda
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
# printing original list
print ("The original list is : " + str(test_list))
# using sort() + lambda
# to sort list of list
# sort by second index
test_list.sort(key = lambda test_list: test_list[1])
# printing result
print ("List after sorting by 2nd element of lists : " + str(test_list))
输出 :
The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]
方法2:使用sorted() + itemgetter()
这也可以应用于执行此特定任务。它具有的优点是它不会修改原始列表。 itemgetter()
用于获取需要执行排序操作的索引元素。
# Python3 code to demonstrate
# to sort list of list by given index
# using sorted() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
# printing original list
print ("The original list is : " + str(test_list))
# using sort() + lambda
# to sort list of list
# sort by second index
res = sorted(test_list, key = itemgetter(1))
# printing result
print ("List after sorting by 2nd element of lists : " + str(res))
输出 :
The original list is : [['Rash', 4, 28], ['Varsha', 2, 20], ['Nikhil', 1, 20], ['Akshat', 3, 21]]
List after sorting by 2nd element of lists : [['Nikhil', 1, 20], ['Varsha', 2, 20], ['Akshat', 3, 21], ['Rash', 4, 28]]