Python - 按行中位数对矩阵进行排序
给定一个矩阵,按每行的中位数排序。
Input : test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
Output : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]]
Explanation : 2 < 3 < 4 < 6, sorted increasingly by median element.
Input : test_list = [[3, 4, 7], [1, 7, 2], [8, 6, 5]]
Output : [[1, 7, 2], [3, 4, 7], [8, 6, 5]]
Explanation : 2 < 3 < 6, sorted increasingly by median element.
方法#1:使用sort()+median()
在这里,我们使用sort()进行排序,并且使用计算中位数的统计函数中位数来计算中位数, median() 。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Row Median
# Using sort() + median()
from statistics import median
def med_comp(row):
# computing median
return median(row)
# initializing list
test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
# printing original list
print("The original list is : " + str(test_list))
# inplace sorting using sort()
test_list.sort(key = med_comp)
# printing result
print("Sorted Matrix : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Row Median
# Using sorted() + lambda + median()
from statistics import median
# initializing list
test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
# printing original list
print("The original list is : " + str(test_list))
# inplace sorting using sort()
res = sorted(test_list, key = lambda row : median(row))
# printing result
print("Sorted Matrix : " + str(res))
输出
The original list is : [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
Sorted Matrix : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]]
方法 #2:使用 sorted() + lambda + medium()
在这里,我们使用sorted()执行排序任务,并且使用lambda函数作为关键函数而不是外部函数。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by Row Median
# Using sorted() + lambda + median()
from statistics import median
# initializing list
test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
# printing original list
print("The original list is : " + str(test_list))
# inplace sorting using sort()
res = sorted(test_list, key = lambda row : median(row))
# printing result
print("Sorted Matrix : " + str(res))
输出
The original list is : [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]]
Sorted Matrix : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]]