Python – 按第 K 列对矩阵行进行反向排序
有时,在处理数据时,我们可能会遇到一个问题,即我们需要根据分数等决定性因素对每一行记录进行排序。这种问题在竞争性编程和 Web 开发中很常见。让我们讨论可以执行此任务的某些方式。
方法 #1:使用sorted()
+ lambda + reverse
上述方法的组合可用于执行此任务。在此,我们使用 lambda函数和列表推导对特定列使用反向对列表进行降序排序。
# Python3 code to demonstrate
# Reverse sort Matrix Row by Kth Column
# using sorted() + lambda + reverse()
# Initializing list
test_list = [['Manjeet', 65], ['Akshat', 42], ['Akash', 38], ['Nikhil', 192]]
# printing original lists
print("The original list is : " + str(test_list))
# Initializing K
K = 1
# Reverse sort Matrix Row by Kth Column
# using sorted() + lambda + reverse()
res = sorted(test_list, key = lambda ele: ele[K], reverse = True)
# printing result
print ("List after performing sorting of matrix records : " + str(res))
The original list is : [[‘Manjeet’, 65], [‘Akshat’, 42], [‘Akash’, 38], [‘Nikhil’, 192]]
List after performing sorting of matrix records : [[‘Nikhil’, 192], [‘Manjeet’, 65], [‘Akshat’, 42], [‘Akash’, 38]]
方法 #2:使用sort() + itemgetter()
上述方法的组合也可以用来解决这个问题。在此,我们使用 itemgetter 执行 lambda函数的任务,而 sort() 执行排序。
# Python3 code to demonstrate
# Reverse sort Matrix Row by Kth Column
# using sort() + itemgetter()
from operator import itemgetter
# Initializing list
test_list = [['Manjeet', 65], ['Akshat', 42], ['Akash', 38], ['Nikhil', 192]]
# printing original lists
print("The original list is : " + str(test_list))
# Initializing K
K = 1
# Reverse sort Matrix Row by Kth Column
# using sort() + itemgetter()
test_list.sort(key = itemgetter(K), reverse = True)
# printing result
print ("List after performing sorting of matrix records : " + str(test_list))
The original list is : [[‘Manjeet’, 65], [‘Akshat’, 42], [‘Akash’, 38], [‘Nikhil’, 192]]
List after performing sorting of matrix records : [[‘Nikhil’, 192], [‘Manjeet’, 65], [‘Akshat’, 42], [‘Akash’, 38]]