Python程序按最大行元素对矩阵进行排序
给定一个矩阵,按最大元素对行进行排序。
Input : test_list = [[5, 7, 8], [9, 10, 3],
[10, 18, 3], [0, 3, 5]]
Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]
Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted.
Input : test_list = [[9, 10, 3],
[10, 18, 3], [0, 3, 5]]
Output : [[10, 18, 3], [9, 10, 3], [0, 3, 5]]
Explanation : 18, 10, and 5 are maximum elements in rows, hence sorted.
方法 #1:使用 sort() + max()
在这里,我们使用 sort() 执行排序任务,键是每行的最大元素。 reverse 关键字用于通过在开始时保持最大元素行并从那里减少来进行排序。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using sort() + max()
def max_sort(row):
return max(row)
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
[10, 18, 3], [0, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
# sort() for sorting, max to get maximum values
test_list.sort(key = max_sort, reverse = True)
# printing result
print("The maximum sorted Matrix : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using sorted() + lambda + max()
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
[10, 18, 3], [0, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
# sorted() for sorting, max to get maximum values
# reverse for reversed order
res = sorted(test_list, key = lambda row : max(row), reverse=True)
# printing result
print("The maximum sorted Matrix : " + str(res))
输出:
The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]
The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]
方法 #2:使用 sorted() + lambda + max()
在此,我们使用 sorted() 执行非就地排序的排序任务,并使用 lambda函数代替外部函数来包含行逻辑中的最大元素。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by Maximum Row element
# Using sorted() + lambda + max()
# initializing list
test_list = [[5, 7, 8], [9, 10, 3],
[10, 18, 3], [0, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
# sorted() for sorting, max to get maximum values
# reverse for reversed order
res = sorted(test_list, key = lambda row : max(row), reverse=True)
# printing result
print("The maximum sorted Matrix : " + str(res))
输出:
The original list is : [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]]
The maximum sorted Matrix : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]]