Python程序以最大总和打印特定数量的行
给定一个矩阵,以下文章提取具有最大总和的指定行数。
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]], K = 3
Output : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]
Explanation : 199 > 20 > 18, 3 maximum elements rows are extracted.
Input : test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]], K = 2
Output : [[199], [2, 3, 4, 5, 6]]
Explanation : 199 > 20, 2 maximum elements rows are extracted.
方法一:使用sorted(), 逆转, 切片和求和()
在这里,我们使用 sorted() 执行排序任务并使用 sum() 获取总和。反向键用于执行行的反转以获得顶部的最大求和行,然后对顶部 K(特定行数)行进行切片。
Python3
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sorted gets reverse sorted matrix by sum
# K rows extracted using slicing
res = sorted(test_list, key=lambda row: sum(row), reverse=True)[:K]
# printing result
print("The filtered rows : " + str(res))
Python3
# row sum util.
def row_sum(row):
return sum(row)
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sort() used to sort
# K rows extracted using slicing
test_list.sort(key=row_sum, reverse=True)
res = test_list[:K]
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]
方法 2:使用sort() 、 reverse 、 slicing和sum()
在此,我们使用 sort() 执行就地排序任务,使用 reverse 作为关键字。切片是使用切片操作完成的。 sum() 用于求和,并调用外部函数来计算列表行的总和。
蟒蛇3
# row sum util.
def row_sum(row):
return sum(row)
# initializing list
test_list = [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 3
# sort() used to sort
# K rows extracted using slicing
test_list.sort(key=row_sum, reverse=True)
res = test_list[:K]
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[3, 4, 5, 6], [1, 4, 6], [199], [2, 3, 4, 5, 6], [7, 3, 1]]
The filtered rows : [[199], [2, 3, 4, 5, 6], [3, 4, 5, 6]]