基于行总和对矩阵进行排序的Python程序
给定一个矩阵,根据行的总和执行排序。
Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]
Explanation : 3 < 9 < 11 < 14. Sorted sum.
Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]]
Output : [[4, 5], [4, 6, 1], [2, 5, 7]]
Explanation : 9 < 11 < 14. Sorted sum.
方法 #1:使用 sort() + sum()
其中,排序任务使用sort()完成,sum的计算由sum()完成,并作为键fnc传递。排序()。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by row sum
# Using sort() + sum()
# helper_fnc
def sum_sort(row):
# getting sum
return sum(row)
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
# using sort() to perform sort
test_list.sort(key = sum_sort)
# printing result
print("Sum sorted Matrix : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by row sum
# Using sorted() + sum() + lambda
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
# using lambda function preventing fnc. call
res = sorted(test_list, key=lambda row: sum(row))
# printing result
print("Sum sorted Matrix : " + str(res))
输出:
The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]
方法 #2:使用sorted() + sum() + lambda
在这种情况下,排序任务是使用 sorted() 完成的,并且使用 lambda 代替键的外部函数调用。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by row sum
# Using sorted() + sum() + lambda
# initializing list
test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
# printing original list
print("The original list is : " + str(test_list))
# using lambda function preventing fnc. call
res = sorted(test_list, key=lambda row: sum(row))
# printing result
print("Sum sorted Matrix : " + str(res))
输出:
The original list is : [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]]
Sum sorted Matrix : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]]