根据主要和次要索引对矩阵行进行排序的Python程序
给定 Matrix,这里的任务是编写一个Python程序来根据主要和次要索引对行进行排序。首先使用主索引,行将根据每行在指定主索引处的元素进行排列。现在,如果两行在给定的主索引处具有相同的元素,则将使用二级索引再次执行排序。
Input : test_list = [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]], pri, sec = 3, 2
Output : [[10, 1, 1, 4], [2, 5, 7, 4], [9, 1, 9, 4], [8, 1, 3, 10]]
Explanation : Sorted by 3rd index, and then by 2nd index in case of equal elements in 3rd index.
Input : test_list = [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]], pri, sec = 1, 2
Output : [[10, 1, 1, 4], [8, 1, 3, 10], [9, 1, 9, 4], [2, 5, 7, 4]]
Explanation : Sorted by 1st index, and then by 2nd index in case of equal elements in 1st index.
方法 1:使用sort()和lambda
这使用 sort() 执行就地排序,并且 lambda函数用于使用按 lambda函数的键中的 order 中定义的排序顺序执行排序。
程序:
Python3
# initializing list
test_list = [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing pri, sec
pri, sec = 3, 2
# inplace sorting using sort()
test_list.sort(key=lambda ele: (ele[pri], ele[sec]))
# printing result
print("Matrix after sorting : " + str(test_list))
Python3
import operator
# initializing list
test_list = [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing pri, sec
pri, sec = 3, 2
# inplace sorting using sort()
res = sorted(test_list, key=operator.itemgetter(pri, sec))
# printing result
print("Matrix after sorting : " + str(res))
输出:
The original list is : [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]]
Matrix after sorting : [[10, 1, 1, 4], [2, 5, 7, 4], [9, 1, 9, 4], [8, 1, 3, 10]]
方法 2:使用sorted()和itemgetter()
在这里,我们使用 sorted() 执行排序任务, itemgetter() 用于执行根据需要获取索引的任务。
程序:
蟒蛇3
import operator
# initializing list
test_list = [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing pri, sec
pri, sec = 3, 2
# inplace sorting using sort()
res = sorted(test_list, key=operator.itemgetter(pri, sec))
# printing result
print("Matrix after sorting : " + str(res))
输出:
The original list is : [[2, 5, 7, 4], [8, 1, 3, 10], [9, 1, 9, 4], [10, 1, 1, 4]]
Matrix after sorting : [[10, 1, 1, 4], [2, 5, 7, 4], [9, 1, 9, 4], [8, 1, 3, 10]]