📜  基于行总和对矩阵进行排序的Python程序

📅  最后修改于: 2022-05-13 01:54:38.498000             🧑  作者: Mango

基于行总和对矩阵进行排序的Python程序

给定一个矩阵,根据行的总和执行排序。

方法 #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))


输出:

方法 #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))

输出: